package com.cci.kangdao.crmapi;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.common.ApplicationContextUtils;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.dto.request.AccountEngineRelaRequest;
import com.cci.kangdao.escalation.dao.EscalationReasonTDao;
import com.cci.kangdao.escalation.dto.response.GetEscalationOrderDetailResponse;
import com.cci.kangdao.escalation.model.EscalationOrderT;
import com.cci.kangdao.escalation.model.EscalationReasonT;
import com.cci.kangdao.escalation.model.type.TypeDictionary;
import com.cci.kangdao.escalation.service.EscalationService;
import com.cci.kangdao.exception.CommonException;
import com.cci.kangdao.exception.ExceptionStatus;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.NoticeService;
import com.cci.kangdao.service.WorkOrderSynchroService;
import com.cci.kangdao.service.impl.WorkOrderTServiceImpl;
import com.cci.kangdao.utilTool.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

//app同步crm相关接口
/**
 * @ClassName CRMServiceApiImpl
 * @Description TODO
 * @Author leonbreeze
 * @Date 2019/1/19 11:27 AM
 * @Version 1.0
 **/
@Service("crmServiceApi")
public class CRMServiceApiImpl implements CRMServiceApi {

	/** 1、日志 */
	private static final Logger LOG = Logger.getLogger(CRMServiceApiImpl.class);

	@Resource
	private WorkOrderTDao workOrderTDao;

	@Resource
	private CRMPlatformServiceDao crmPlatformServiceDao;

	@Resource
	private RedisClientUtils redisClient;

	@Resource
	private EscalationService escalationService;

	@Resource
	private EscalationReasonTDao escalationReasonTDao;

	@Autowired
	private RedisClientUtils redisClientUtils;

	@Resource
	private CRMPlatformServiceDao crmServiceDao;

	@Resource
	private ServiceStationDao serviceStationDao;

	@Resource
	private SSRepairTDao sSRepairTDao;

	@Resource
	private WorkOrderTServiceImpl workOrderTServiceImpl;

	@Autowired
	private WorkOrderRepairDao workOrderRePairDao;

	@Resource
	private NoticeService noticeService;
	@Resource
	private DictionariesTDao dictionariesTDao;
	@Resource
	private WorkOrderSynchroService workOrderSynchroService;

	/**
	 * 根据esn获取sf设备信息
	 * @param channelName
	 * @param esn
	 * @return
	 */
	@Override
	public CRMResponeEntity verifyEngineInfo(String channelName, String esn) {

		/**
		 * 1、初始化响应实体
		 */
		CRMResponeEntity verfyRespone = this.verifyParameters(channelName);
		if (verfyRespone.getStatus() == CRMServiceConst.CHANNEL_VERIFY_FAILURE) {
			return verfyRespone;
		}
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		if (esn == null || esn.length() == 0) {
			/**
			 * 2、传递参数为空
			 */
			responeEntity.setMessage("发动机号不能为空");
			responeEntity.setStatus(1);
			return responeEntity;
		}

		/**
		 * 3、判断渠道
		 **/
		if (channelName.equals(CRMServiceConst.DCEC) || channelName.equals(CRMServiceConst.DCEC_TEST)) {

			/**
			 * 3.1、DCEC请求处理逻辑
			 */
			// 请求Param参数
			Map<String, Object> bodyParameter = new HashMap<String, Object>();
			bodyParameter.put("ESN", esn);
//			bodyParameter.put("ESN", "78821234");
			JSONObject jsonBodyParameter = JSONObject.fromObject(bodyParameter);

			// body请求参数
//            Map<String, Object> requestParameter = new HashMap<String, Object>();
//            requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "getEngineInfo");
//            requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBodyParameter.toString());
			// DCEC获取token及host
			Map<String, Object> map = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(map)){
				return this.getNullTokenResponeEntity();
			}
//            Map<String,Object> headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(map,"token"));
			String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.VERIFY_ENGINEINFO;
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
					MapUtils.getString(map, "token"), JsonUtils.toJsonString(bodyParameter));
			// 将响应消息转换成响应实体类
			return this.getResponeEntity(responseDate, "数据获取成功");

		} else if (channelName.equals(CRMServiceConst.XCEC) || channelName.equals(CRMServiceConst.XCEC_TEST)) {
			/**
			 * 3.2、XCEC请求处理逻辑
			 */
			// 请求Param参数
			Map<String, Object> requestParameter = new HashMap<String, Object>();
			requestParameter.put("ESN", esn);
			// 打印参数
			System.out.println(JsonUtils.toJsonString(requestParameter));
			// 添加加密请求头
			Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
			if (tokenAndHostMap == null) {
				return this.getNullTokenResponeEntity();
			}
			// 添加token请求头
			Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);
			// 调取请求
			String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "") + CRMServiceConst.VERIFY_ENGINEINFO;
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);

			// 将响应消息转换成响应实体类
			return this.getResponeEntity(responseDate, "数据获取成功");
		} else if (channelName.equals(CRMServiceConst.BFCEC) || channelName.equals(CRMServiceConst.BFCEC_TEST)) {

		} else if (channelName.equals(CRMServiceConst.DBU) || channelName.equals(CRMServiceConst.DBU_TEST)) {

			/**
			 * 3.2、CCI请求处理逻辑
			 */
			// 请求Param参数
			Map<String, Object> requestParameter = new HashMap<String, Object>();
			requestParameter.put("ESN", esn);
			// 打印参数
			System.out.println(JsonUtils.toJsonString(requestParameter));
			// 添加加密请求头
			Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
			if (tokenAndHostMap == null) {
				return this.getNullTokenResponeEntity();
			}
			// 添加token请求头
			Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
			// 调取请求
			String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "") + CRMServiceConst.VERIFY_ENGINEINFO;
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
			// 将响应消息转换成响应实体类
			return this.getResponeEntity(responseDate, "数据获取成功");
		}

		return null;
	}

    /**
     * XCEC同步工单信息
     *
     * @param channelName
     * @param redisClientUtils
     * @param serviceDao
     * @param parameter
     * @return
     */

    private CRMResponeEntity xcecsyncAppOrderInfoToCRM(String channelName, RedisClientUtils redisClientUtils, CRMPlatformServiceDao serviceDao, Map<String, Object> parameter,WorkOrderSynchroT workOrderSynchro) {
        // 请求Param参数
        String appOrderNo = parameter.get("orderNo").toString();
        /**
         * 3.2、XCEC请求处理逻辑
         */
        // 请求Param参数
        if (redisClientUtils != null) {// APP操作同步，非重传，参数需要做处理

            if (parameter.containsKey("city") && parameter.get("city") != null) {
                if (parameter.get("city").toString().contains("北京市")) {
                    parameter.put("city", "北京城区");
                } else if (parameter.get("city").toString().contains("天津市")) {
                    parameter.put("city", "天津城区");
                } else if (parameter.get("city").toString().contains("上海市")) {
                    parameter.put("city", "上海城区");
                } else if (parameter.get("city").toString().contains("重庆市")) {
                    parameter.put("city", "重庆城区");
                } else if (parameter.get("city").toString().contains("重庆")) {
                    parameter.put("city", "重庆郊县");
                }

            }
            // 请求Param参数
            this.addInterfaceNullParameters("syncAppOrderInfoToCRM", parameter);
            parameter.put("serviceChannel", "XCEC");

        }

//			System.out.println(JsonUtils.toJsonString(parameter));
        // 添加加密请求头
        Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
        if (tokenAndHostMap == null || tokenAndHostMap.isEmpty()) {
			/**
			 * 注释log
			 * 20230808
			 * sxt 处理Privacy Violation
			 */
            //LOG.error("XCEC 同步工单信息获取token失败；打印参数" + JsonUtils.toJsonString(parameter));
			workOrderSynchro.setFailReason("获取token失败");
			workOrderSynchro.setSyncStatus(0);
            return this.getNullTokenResponeEntity();
        }
        // 添加token请求头
        Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);
        // 调取请求
        String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
                + CRMServiceConst.SYNC_APPORDERINFO_TOCRM;
        JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestXCEC(channelHost, headerParameter, parameter);
        /**
         * 4、保存异常工单数据到redis
         **/
        if (isSaveWorkOrderWithXCEC(responseDate)) {
			workOrderSynchro.setFailReason(null != responseDate ? responseDate.toString() : "返回值空");
			workOrderSynchro.setSyncStatus(0);
        }

        // 将响应消息转换成响应实体类
        CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
        if (!isSaveWorkOrderWithXCEC(responseDate) && responeEntity.getData().containsKey("CRMNo")) {
			workOrderSynchro.setOrderNoCrm(responeEntity.getData().get("CRMNo").toString());
			workOrderSynchro.setSyncStatus(1);
            Map<String, Object> updateOrderMap = new HashMap<>();
            updateOrderMap.put("OrderNo", appOrderNo);
            updateOrderMap.put("OrderNoCrm", responeEntity.getData().get("CRMNo"));
            int updateSuccess = serviceDao.updateWOrkOrderByOrderNo(updateOrderMap);
        }
        // 将响应消息转换成响应实体类
        return responeEntity;
    }

	/**
	 * 同步工单信息
	 * @param channelName
	 * @param serviceDao
	 * @param redisClientUtils
	 * @param parameter
	 * @return
	 */
	@Override
	public CRMResponeEntity syncAppOrderInfoToCRM(String channelName, CRMPlatformServiceDao serviceDao, RedisClientUtils redisClientUtils, Map<String, Object> parameter,Long synchroId) {
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		WorkOrderSynchroT workOrderSynchro = new WorkOrderSynchroT();
		int synchroCount = 1;
		/**
		 * 1、初始化响应实体
		 */
        /*CRMResponeEntity verfyRespone = this.verifyParameters(channelName);
        if (verfyRespone.getStatus() == CRMServiceConst.CHANNEL_VERIFY_FAILURE) {
            return verfyRespone;
        }*/
		// 请求Param参数
		String appOrderNo = parameter.get("orderNo").toString();
		try {
			/**
			 * 3、判断渠道
			 **/
			if (channelName.equals(CRMServiceConst.DCEC) || channelName.equals(CRMServiceConst.DCEC_TEST)) {

				/**
				 * 3.1、DCEC请求处理逻辑
				 */
				/**
				 * @update 2022-12-21
				 * @description dcec amt项目新增需求
				 */
				// 请求Param参数
				// 增加新字段是否存在的判断：natureClaim，emergencyMode，provice，city,area
				if ((StringUtils.isEmpty(MapUtils.getString(parameter, "natureClaim"))
						|| StringUtils.isEmpty(MapUtils.getString(parameter, "emergencyMode"))
						|| StringUtils.isEmpty(MapUtils.getString(parameter, "provice"))
						|| StringUtils.isEmpty(MapUtils.getString(parameter, "city"))
						|| StringUtils.isEmpty(MapUtils.getString(parameter, "area")))
						&& (StringUtils.isEmpty(MapUtils.getString(parameter, "workHours"))
						&& StringUtils.isEmpty(MapUtils.getString(parameter, "workMileages")))) {
					responeEntity.setStatus(1);
					responeEntity.setMessage("缺少必要参数！");
					responeEntity.setData(new JSONObject());
					return responeEntity;
				}


				/**
				 * @update 2022-12-26
				 * DCEC amt工单需求
				 * 新增3个参数，判断参数是否为空
				 * 【变速箱序列号】，amtNo
				 * 【保修性质】，warrantyNature
				 * 【故障发生时间】，faultHappenTime
				 *
				 **/
				if (StringUtils.isEmpty(MapUtils.getString(parameter, "ESN"))) {
					if ((StringUtils.isEmpty(MapUtils.getString(parameter, "amtNo"))
							&& StringUtils.isEmpty(MapUtils.getString(parameter, "warrantyNature"))
					)) {
						if (StringUtils.isEmpty(MapUtils.getString(parameter, "faultHappenTime"))) {
							parameter.put("faultHappenTime", Date_Util.getOnlyDate());
						} else {
							String faultHappenTime = MapUtils.getString(parameter, "faultHappenTime");
							try {
								faultHappenTime = Date_Util.getOnlyDate(faultHappenTime);
							} catch (ParseException p) {
								p.printStackTrace();
							}
							parameter.put("faultHappenTime", faultHappenTime);
						}
						responeEntity.setStatus(1);
						responeEntity.setMessage("缺少AMT必要参数！");
						responeEntity.setData(new JSONObject());
						return responeEntity;
					}
				}


				if (redisClientUtils != null) {// APP操作同步，非重传，参数需要做处理

					this.addInterfaceNullParameters("syncAppOrderInfoToCRM", parameter);
					parameter.put("serviceChannel", "DCEC");

				}
				/**
				 * deec noApp报修， 工单的workorder的类型为6，但是crm 不识别6 只能将 将workorder改为o
				 */
				int orderSource = (int) parameter.get("orderSource");
				parameter.put("orderSource", orderSource == 6 ? 0 : orderSource);
//            JSONObject jsonBodyParameter = JSONObject.fromObject(parameter);
				List<Map<String, Object>> list = new ArrayList<>();
				list.add(parameter);
				// body请求参数-syncAppWorkOrderInfo
//            Map<String, Object> requestParameter = new HashMap<String, Object>();
//            requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, CRMServiceConst.SYNC_APPORDERINFO_TOCRM);
//            requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBodyParameter.toString());
				// DCEC获取token及host
				Map<String, Object> map = getDCECSfTokenAndHost();
				//获取token失败放到redis中
				if (MapUtils.isEmpty(map)) {
					LOG.info("DCEC 同步信息到crm 获取token失败" + JsonUtils.toJsonString(parameter));
					workOrderSynchro.setFailReason("获取token失败");
					workOrderSynchro.setSyncStatus(0);
					responeEntity = this.getNullTokenResponeEntity();
				} else {
					String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.SYNC_APPORDERINFO_TOCRM;

					/**
					 * 3.2、DCEC接口网络请求
					 * @update 2022-12-26
					 * DCEC amt工单需求
					 * 新增3个参数
					 * 【变速箱序列号】，amtNo 必填
					 * 【保修性质】，warrantyNature 必填
					 * 【故障发生时间】，faultHappenTime 非必填
					 *
					 **/
					JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
							MapUtils.getString(map, "token"), JsonUtils.toJsonString(list));
					/**
					 * 4、服务器异常/超时/关闭，需要保存到redis数据库
					 **/
					if (isSaveWorkOrder(responseDate)) {
						workOrderSynchro.setFailReason(null != responseDate ? responseDate.toString() : "返回值空");
						workOrderSynchro.setSyncStatus(0);
					}
					/**
					 * 5、如果CRM返回CRMNo，更新APP工单表
					 **/
					responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
					if (!isSaveWorkOrder(responseDate) && responeEntity.getData().containsKey("crmNo")) {
						workOrderSynchro.setOrderNoCrm(responeEntity.getData().get("crmNo").toString());
						workOrderSynchro.setSyncStatus(1);
						Map<String, Object> updateOrderMap = new HashMap<>();
						updateOrderMap.put("OrderNo", appOrderNo);
						updateOrderMap.put("OrderNoCrm", responeEntity.getData().get("crmNo"));
						int updateSuccess = serviceDao.updateWOrkOrderByOrderNo(updateOrderMap);
					}
				}
			} else if (channelName.equals(CRMServiceConst.XCEC) || channelName.equals(CRMServiceConst.XCEC_TEST)) {
				//调用xcec新的逻辑；
				responeEntity = xcecsyncAppOrderInfoToCRM(channelName, redisClientUtils, serviceDao, parameter, workOrderSynchro);
			} else if (channelName.equals(CRMServiceConst.BFCEC) || channelName.equals(CRMServiceConst.BFCEC_TEST)) {

			} else if (channelName.equals(CRMServiceConst.DBU) || channelName.equals(CRMServiceConst.DBU_TEST)) {

				// TODO >>DBU渠道

				// 请求Param参数
				if (redisClientUtils != null) {// APP操作同步，非重传，参数需要做处理
					/**
					 * 3.2、CCI请求处理逻辑
					 */
					if (parameter.containsKey("faultCity") && parameter.get("faultCity") != null) {
						if (parameter.get("faultCity").toString().contains("北京市")) {
							parameter.put("faultCity", "北京城区");
						} else if (parameter.get("faultCity").toString().contains("天津市")) {
							parameter.put("faultCity", "天津城区");
						} else if (parameter.get("faultCity").toString().contains("上海市")) {
							parameter.put("faultCity", "上海城区");
						} else if (parameter.get("faultCity").toString().contains("重庆市")) {
							parameter.put("faultCity", "重庆城区");
						} else if (parameter.get("faultCity").toString().contains("重庆")) {
							parameter.put("faultCity", "重庆郊县");
						}

					}
					if (parameter.containsKey("customerCompanyCity") && parameter.get("customerCompanyCity") != null) {
						if (parameter.get("customerCompanyCity").toString().contains("北京市")) {
							parameter.put("customerCompanyCity", "北京城区");
						} else if (parameter.get("customerCompanyCity").toString().contains("天津市")) {
							parameter.put("customerCompanyCity", "天津城区");
						} else if (parameter.get("customerCompanyCity").toString().contains("上海市")) {
							parameter.put("customerCompanyCity", "上海城区");
						} else if (parameter.get("customerCompanyCity").toString().contains("重庆市")) {
							parameter.put("customerCompanyCity", "重庆城区");
						} else if (parameter.get("customerCompanyCity").toString().contains("重庆")) {
							parameter.put("customerCompanyCity", "重庆郊县");
						}

					}
					// 打印请求参数
					parameter.put("serviceChannel", "CCI");
				}
//			System.out.println(JsonUtils.toJsonString(parameter));
				// 添加加密请求头
				Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
				if (tokenAndHostMap == null || tokenAndHostMap.isEmpty()) {
					/**
					 * 注释log
					 * 20230808
					 * sxt 处理Privacy Violation
					 */
					//LOG.error("DBU 同步工单信息获取token失败；打印参数" + JsonUtils.toJsonString(parameter));
					workOrderSynchro.setFailReason("获取token失败");
					workOrderSynchro.setSyncStatus(0);
					responeEntity = this.getNullTokenResponeEntity();
				} else {
					// 添加token请求头
					Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
					// 调取请求
					String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
							+ CRMServiceConst.SYNC_APPORDERINFO_TOCRM;
					JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameter);
					/**
					 * 4、保存异常工单数据到redis
					 **/
					//报修来源0终端用户APP报修，1服务站APP报修，2用户400报修，3服务站CRM报修，4CRM转派
					int orderSource = MapUtils.getIntValue(parameter, "orderSource", -1);
					//是否是服务站挂号失败     默认不是服务站挂号失败
					boolean isStationRegisterFail = false;
					if (orderSource == 1) {
						if (null != responseDate && responseDate instanceof JSONObject) {
							if (responseDate.containsKey("status")
									&& responseDate.getInt("status") == 2) {
								isStationRegisterFail = true;
							}
						}
					}
					//sprint45  重复挂号需求   服务站报修的工单，sf会进行校验，校验失败的工单不进入重传
					boolean isSuccess = true;
					if (isSaveWorkOrderWithDBU(responseDate) && !isStationRegisterFail) {
						isSuccess = false;
						workOrderSynchro.setFailReason(null != responseDate ? responseDate.toString() : "返回值空");
						workOrderSynchro.setSyncStatus(0);
					}
					// 将响应消息转换成响应实体类
					responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
					if (isSuccess && responeEntity.getData().containsKey("CRMOrderNo")) {
						workOrderSynchro.setOrderNoCrm(responeEntity.getData().get("CRMOrderNo").toString());
						workOrderSynchro.setSyncStatus(1);
						Map<String, Object> updateOrderMap = new HashMap<>();
						updateOrderMap.put("OrderNo", appOrderNo);
						updateOrderMap.put("OrderNoCrm", responeEntity.getData().get("CRMOrderNo"));
						int updateSuccess = serviceDao.updateWOrkOrderByOrderNo(updateOrderMap);
					}

					if (isStationRegisterFail) {  //sprint45服务站报修  sf校验挂号失败的新增逻辑
						//挂号失败逻辑1.修改工单当前状态为39挂号失败  2.保存操作记录表  3.推送短信给经销商站长（报单人员）  4.保存推送记录表
						String currentTime = LocalTimeUtil.getRealCurrentTime();
						//经销商站长（报单人员）id和手机号  从服务站创建工单接口传进map
						long userId = MapUtils.getLongValue(parameter, "Creator", -1);
						String userPhone = MapUtils.getString(parameter, "UserPhone", "");
						String userName = MapUtils.getString(parameter, "UserName", "");
						//挂号失败原因
						String stationRegisterFailReason = StringUtils.isEmpty(responeEntity.getMessage()) ? "CRM未返回挂号失败原因" : responeEntity.getMessage();
						//1.修改工单当前状态为39挂号失败
						Map<String, Object> updateOrderMap = new HashMap<>();
						updateOrderMap.put("OrderNo", appOrderNo);
						updateOrderMap.put("OrderStatus", 39);
						updateOrderMap.put("UpdateTime", currentTime);
						updateOrderMap.put("Updator", userId);
						int updateSuccess = serviceDao.updateWorkOrderInfoByOrderNoFromCRM(updateOrderMap);
						//2.保存操作记录表
						Long orderId = MapUtils.getLong(parameter, "OrderId", -1L);
						String IMEI = MapUtils.getString(parameter, "IMEI", "");
						String locLon = MapUtils.getString(parameter, "LocLon", "");
						String locLat = MapUtils.getString(parameter, "LocLat", "");
						String location = MapUtils.getString(parameter, "ProLocation", "");
						workOrderTServiceImpl.saveOperation(orderId, userId, 39, stationRegisterFailReason, locLon, locLat, location, IMEI, 0, userId,
								currentTime);
						//3.推送短信和app提醒给经销商站长（报单人员）
						//根据工单id获取工单信息
						WorkOrderT workOrderT = workOrderTDao.getWorkOrderByOrderId(orderId);
						String content = "您的服务工单" + appOrderNo + "，属于\"" + workOrderT.getSellType() + "\"" + (StringUtils.isNotBlank(workOrderT.getServiceSubtype()) ? "-" + workOrderT.getServiceSubtype() : "") + "，" + "挂号失败，失败原因：" + stationRegisterFailReason;
						String smsResult = SmsUtils.sendMessage(userPhone, content);
						//4.保存推送记录表
						List<Map<String, Object>> notifyRecordList = new ArrayList<>();
						Map<String, Object> smsNotifyRecord = workOrderTServiceImpl.saveMsgOperation(orderId, 2, 1, userId, content, 1, currentTime, String.format("%s发送状态:%s", userPhone, smsResult), userId);
						notifyRecordList.add(smsNotifyRecord);
						if (CollectionUtils.isNotEmpty(notifyRecordList)) {
							workOrderRePairDao.saveMsgOperation(notifyRecordList);
						}
						//推送app提醒并入库
						noticeService.push(2, 1, orderId, userId, userName, "新工单提醒",
								content, content, userId);
					}
				}
			} else if (channelName.equals(CRMServiceConst.CCEC)) {
				// return getSuccessEntity("屏蔽CRM代码");
				// CCEC同步工单信息至CRM
				Boolean retry = MapUtils.getBoolean(parameter, "retry", Boolean.FALSE);

				// 拼装请求参数Map
				if (!retry) {
					String requestType = MapUtils.getString(parameter, "requestType", "");
					// APP操作同步，非重传，参数需要做处理
					if (StringUtils.isNotBlank(requestType) && requestType.equals("2")) {
						return getSuccessEntity("CCEC非报修工单信息不需要同步CRM");
					}

					this.addInterfaceNullParameters("syncAppOrderInfoToCRM", parameter);
					// 再次反向处理经纬度，因为之前的方法了反向处理了一次，还得反回来。
					parameter.put("faultLon", MapUtils.getDoubleValue(parameter, "faultLat", 0.0));
					parameter.put("faultLat", MapUtils.getDoubleValue(parameter, "faultLon", 0.0));
					parameter.put("serviceChannel", "CCEC");
				}

				// body请求参数
				Map<String, Object> requestParameter = new HashMap<>();
				requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncAppWorkOrderInfo");
				requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, JsonUtils.toJsonString(parameter));
				// 添加加密请求头
				Map<String, Object> headerParameter = this.addEncryptionHeader(requestParameter);
				// 获取渠道Host
				String channelHost = this.getChannelHostByChannelName(channelName);
				// CCEC接口网络请求
				JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
				// 服务器异常/超时/关闭，需要保存到redis异常重试信息中
				if (isExceptionResponse(responseDate)) {
					// 非重试，加入重试队列
					if (!retry) {
						saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_ORDER_INFO, appOrderNo, parameter);
					}
				}
				// 如果CRM 正常返回数据，更新数据表
				CRMResponeEntity responseEntity = this.getResponeEntity(responseDate, "数据获取成功");
				if (responseEntity.getData().containsKey("CCSSComplainerOrderNo")) {
					Map<String, Object> updateOrderMap = new HashMap<>();
					updateOrderMap.put("OrderNo", appOrderNo);
					updateOrderMap.put("OrderNoCrm", responseEntity.getData().get("CCSSComplainerOrderNo"));
					int updateSuccess = serviceDao.updateWOrkOrderByOrderNo(updateOrderMap);
				}
				// 将响应消息转换成响应实体类
				return responseEntity;
			}
		} catch (Exception e){
			LOG.error(e.getMessage(), e);
		} finally {
			workOrderSynchro.setOrderNo(appOrderNo);
			workOrderSynchro.setChannelName(channelName);
			workOrderSynchro.setProcessStatus(1);
			workOrderSynchro.setOrderInfo(JSON.toJSONString(parameter));
			if(null != synchroId){
				WorkOrderSynchroT synchroT = workOrderSynchroService.selectById(synchroId);
				if(null != synchroT){
					synchroCount = synchroT.getSynchroCount();
				}
				workOrderSynchro.setSynchroCount(synchroCount + 1);
				workOrderSynchro.setId(synchroId);
				workOrderSynchroService.updateById(workOrderSynchro);
			} else {
				workOrderSynchroService.add(workOrderSynchro);
			}
			//发送邮件通知
			if(workOrderSynchro.getSyncStatus() == 0 && synchroCount < 3){
				MailUtilException.sendMail("工单号：" + appOrderNo + "同步信息失败", "失败原因:" + workOrderSynchro.getFailReason(), channelName);
			}
		}
		return responeEntity;
	}

	/**
	 *
	 * <p>
	 * Title: getRecommendedServiceStations
	 * </p>
	 *
	 * @param channelName 渠道
	 * @param param       参数
	 * @return
	 */
	@Override
	public CRMResponeEntity getRecommendedServiceStations(String channelName, Map<String, Object> param) {
		/**
		 * 1、初始化响应实体
		 */
		CRMResponeEntity verifyResponse = this.verifyParameters(channelName);
		if (verifyResponse.getStatus() == CRMServiceConst.CHANNEL_VERIFY_FAILURE) {
			return verifyResponse;
		}

		/**
		 * 2、重组经纬度数据（经纬度与crm接口文档定义相反）
		 */
		Double positionLat = (Double) param.get("positionLon");
		Double positionLon = (Double) param.get("positionLat");

		Map<String, Object> crmMap = new HashMap<>();
		crmMap.putAll(param);
		crmMap.put("positionLat", positionLat);
		crmMap.put("positionLon", positionLon);

		// 请求Param参数
		JSONObject jsonBodyParameter = JSONObject.fromObject(crmMap);

		// body请求参数
		Map<String, Object> requestParameter = new HashMap<String, Object>();
		requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncReStationInfos");
		requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBodyParameter.toString());
		Map<String, Object> headerParameter = new HashMap<>();
		String channelHost = "";
		if (channelName.equals(CRMServiceConst.DCEC)) {
			Map<String, Object> map = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(map)){
				return this.getNullTokenResponeEntity();
			}
			// 添加加密请求头
			headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(map, "token"));
			// 调取请求
			channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.GET_RECOMMENDEDSERVICESTATIONS;
		} else {
			// 添加加密请求头
			headerParameter = this.addEncryptionHeader(requestParameter);
			// 调取请求
			channelHost = this.getChannelHostByChannelName(channelName);
		}
		List<Map<String, Object>> list = new ArrayList<>();
		list.add(param);
		JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
				MapUtils.getString(getDCECSfTokenAndHost(), "token"), JsonUtils.toJsonString(list));

		LOG.info("responseDate:" + responseDate);
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		if (responseDate.getInt("status") == 0) { // 成功
			/**
			 * 3、配置响应实体 data数据
			 */
			JSONObject jsonObject = new JSONObject();
			if (responseDate.get("data") instanceof JSONArray) {
				jsonObject.put("stationInfos", responseDate.getJSONArray("data"));
			} else {
				jsonObject.put("stationInfos", responseDate.getJSONObject("data"));
			}
			responeEntity.setData(jsonObject);
			/**
			 * 4、配置响应实体 message、status数据
			 */
			responeEntity.setMessage("数据获取成功");
			responeEntity.setStatus(0);

		} else // 失败
		{
			/**
			 * 4、配置响应实体 message、status数据
			 */
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			jsonObject.put("stationInfos", jsonArray);
			responeEntity.setData(jsonObject);
			responeEntity.setMessage(responseDate.get("msg").toString());
			responeEntity.setStatus(-1);

		}

		return responeEntity;
	}

	@Override
	public CRMResponeEntity updateServiceStationLonAndLatInfos(String channalName,
                                                               List<Map<String, Object>> lonAndLatInfos) {
        /**
         * 1、初始化响应实体
         */
        CRMResponeEntity verfyRespone = this.verifyParameters(channalName);
        if (verfyRespone.getStatus() == CRMServiceConst.CHANNEL_VERIFY_FAILURE) {
            return verfyRespone;
        }
        /**
         * 2、判断渠道
         **/
        if (channalName.equals(CRMServiceConst.DCEC) || channalName.equals(CRMServiceConst.DCEC_TEST)) {

            // 请求Param参数
            JSONArray lonAndLatArray = JSONArray.fromObject(lonAndLatInfos);
            Map<String, Object> requestParameter = new HashMap<String, Object>();
            requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME,
                    CRMServiceConst.UPDATE_SERVICESTATIONLONANDLATINFOS);
            requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, lonAndLatArray.toString());
            // DCEC获取token及host
            Map<String, Object> map = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(map)){
				return this.getNullTokenResponeEntity();
			}
            Map<String, Object> headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(map, "token"));
            String channelHost = MapUtils.getString(map, "hostUrl")
                    + CRMServiceConst.UPDATE_SERVICESTATIONLONANDLATINFOS;
            JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
                    MapUtils.getString(map, "token"), lonAndLatArray.toString());// CRMHttpClientUtil.httpPOSTRequest(channelHost,
            // headerParameter,requestParameter);

            // 将响应消息转换成响应实体类
            return this.getResponeEntity(responseDate, "服务站经纬度数据同步成功");

        } else if (channalName.equals(CRMServiceConst.XCEC) || channalName.equals(CRMServiceConst.XCEC_TEST)) {
            /**
             * 3.2、XCEC请求处理逻辑
             */
            // 添加加密请求头
            Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
            if (tokenAndHostMap == null) {
                return this.getNullTokenResponeEntity();
            }
            // 添加token请求头
            String tokenStr = MapUtils.getString(tokenAndHostMap, "token", "");
            // 增加Header
            Header auth = new BasicHeader("Authorization", tokenStr);
            // 调取请求
            String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
                    + CRMServiceConst.UPDATE_SERVICESTATIONLONANDLATINFOS;
            String response = HttpUtils.postJson(channelHost, JsonUtils.toJsonString(lonAndLatInfos),
                    new ResponseHandler<String>() {
                        @Override
                        public String handleResponse(HttpResponse response)
                                throws ClientProtocolException, IOException {
                            // 200正常响应
                            if (response.getStatusLine().getStatusCode() == 200) {
                                HttpEntity httpEntity = response.getEntity();
                                return EntityUtils.toString(httpEntity, CRMServiceConst.CRM_RESPONSE_ENCODE_UTF8);
                            } else {
                                LOG.error("同步经纬度数据调用XCEC渠道CRM异常，response:" + response);
                            }
                            return null;
                        }
                    }, auth);
            // 将响应消息转换成响应实体类
            if (StringUtils.isNotEmpty(response)) {
                return JsonUtils.toJavaObject(response, CRMResponeEntity.class);
            } else {
                return null;
            }
        } else if (channalName.equals(CRMServiceConst.BFCEC) || channalName.equals(CRMServiceConst.BFCEC_TEST)) {

        } else if (channalName.equals(CRMServiceConst.DBU) || channalName.equals(CRMServiceConst.DBU_TEST)) {
            // 获取token和url
            Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
            String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
                    + CRMServiceConst.UPDATE_STATIONADDRESS_TOCRM;
            String tokenStr = MapUtils.getString(tokenAndHostMap, "token", "");
            // 增加Header
            Header auth = new BasicHeader("Authorization", tokenStr);
            String response = HttpUtils.postJson(channelHost, JsonUtils.toJsonString(lonAndLatInfos),
                    new ResponseHandler<String>() {
                        @Override
                        public String handleResponse(HttpResponse response)
                                throws ClientProtocolException, IOException {
                            // 200正常响应
                            if (response.getStatusLine().getStatusCode() == 200) {
                                HttpEntity httpEntity = response.getEntity();
                                return EntityUtils.toString(httpEntity, "UTF-8");
                            } else {
                                LOG.error("同步经纬度数据调用DBU渠道CRM异常，response:" + response);
                            }
                            return null;
                        }
                    }, auth);
            // 将响应消息转换成响应实体类
            if (StringUtils.isNotEmpty(response)) {
                return JsonUtils.toJavaObject(response, CRMResponeEntity.class);
            }
            return null;
        } else if (channalName.equals(CRMServiceConst.CCEC)) {
            JSONArray lonAndLatArray = JSONArray.fromObject(lonAndLatInfos);
            Map<String, Object> requestParameter = new HashMap<String, Object>();
            requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "updateStationLatAndLon");
            requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, lonAndLatArray.toString());
            // 添加加密请求头
            Map<String, Object> headerParameter = this.addEncryptionHeader(requestParameter);

            // 调取请求
            String channelHost = this.getChannelHostByChannelName(channalName);
            JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
            // 将响应消息转换成响应实体类
            return this.getResponeEntity(responseDate, "服务站经纬度数据同步成功");
        }
        return null;
    }

    public CRMResponeEntity syncOrderStatusToCrmXcec(String channalName, CRMPlatformServiceDao serviceDao,
                                                     RedisClientUtils redisClientUtils, Map<String, Object> parameters,WorkOrderSynchroT workOrderSynchro,Long synchroId) {

		if (parameters.containsKey("currentCity") && parameters.get("currentCity") != null) {
			if (parameters.get("currentCity").toString().contains("北京市")) {
				parameters.put("currentCity", "北京城区");
			} else if (parameters.get("currentCity").toString().contains("天津市")) {
				parameters.put("currentCity", "天津城区");
			} else if (parameters.get("currentCity").toString().contains("上海市")) {
				parameters.put("currentCity", "上海城区");
			} else if (parameters.get("currentCity").toString().contains("重庆市")) {
				parameters.put("currentCity", "重庆城区");
			} else if (parameters.get("currentCity").toString().contains("重庆")) {
				parameters.put("currentCity", "重庆郊县");
			}
		}

		if (parameters.containsKey("currentProvice")) {
			String currentCity = parameters.get("currentProvice").toString();
			String LowerCurrentCity = currentCity.toLowerCase();
			String UpperCurrentCity = currentCity.toUpperCase();
			if (LowerCurrentCity.contains("null") || UpperCurrentCity.contains("NULL")) {
				parameters.put("currentProvice", "");
			}
		}

		if (parameters.containsKey("currentCity")) {
			String currentCity = parameters.get("currentCity").toString();
			String LowerCurrentCity = currentCity.toLowerCase();
			String UpperCurrentCity = currentCity.toUpperCase();
			if (LowerCurrentCity.contains("null") || UpperCurrentCity.contains("NULL")) {
				parameters.put("currentCity", "");
			}
		}
		/**
		 * 3.2、XCEC请求处理逻辑
		 */
		this.addInterfaceNullParameters("syncOrderStatusToCrm", parameters);
		double positionLat = MapUtils.getDoubleValue(parameters, "positionLat", 0.0);
		double positionLon = MapUtils.getDoubleValue(parameters, "positionLon", 0.0);
		if (positionLat < 60) {
			parameters.put("positionLat", positionLon);
			parameters.put("positionLon", positionLat);
		}
		/**
		 * 3.3、用户不需要处理的话，进行特殊处理
		 */
		if (parameters.get("billStatus").toString().equals("3")) { // 服务经理审核不通过
			if (parameters.containsKey("refuseType") && parameters.get("refuseType").equals("2")) {// 用户不需要维
				parameters.put("billStatus", 15);
			}
		}
        if(!parameters.containsKey("CRMNo") || parameters.get("CRMNo").equals("")){
			String CRMNo = serviceDao.getCRMOrderNoByAPPOrderNo(parameters.get("orderNo").toString());
			if (CRMNo != null && CRMNo.length() > 0) {
				parameters.put("CRMNo", CRMNo);
			}
		}

        System.out.println(JsonUtils.toJsonString(parameters));
        // 添加加密请求头
        Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();

        if (tokenAndHostMap == null || tokenAndHostMap.isEmpty()) {
            LOG.info("XCEC 同步状态到crm 获取token失败" + JsonUtils.toJsonString(parameters));
			workOrderSynchro.setFailReason("获取token失败");
			workOrderSynchro.setSyncStatus(0);
            return this.getNullTokenResponeEntity();
        }
        // 添加token请求头
        Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);
        // 调取请求
        String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
                + CRMServiceConst.SYNC_ORDERSTATUS_TOCRM;
        //先同步历史的数据
		String appOrderNo = parameters.get("orderNo").toString();
		Boolean syncSuccess = true;
		if (redisClientUtils != null) {
			syncSuccess = syncOrderStatusExceptionXcec(serviceDao, channalName, appOrderNo, synchroId);
		}
        if (syncSuccess) {
			// 执行网络请求
			LOG.info("XCEC开始同步到CRM系统参数信息：" + JsonUtils.toJsonString(parameters) + "请求头信息："
					+ JsonUtils.toJsonString(headerParameter));
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestXCEC(channelHost, headerParameter, parameters);
            // 服务器异常/超时/关闭，需要保存到redis数据库
            if (isSaveWorkOrderWithXCEC(responseDate)) {
				workOrderSynchro.setFailReason(null != responseDate ? responseDate.toString() : "返回值空");
				workOrderSynchro.setSyncStatus(0);
            } else {
				workOrderSynchro.setSyncStatus(1);
			}
            CRMResponeEntity cloneEntity = this.getResponeEntity(responseDate, "数据同步成功");
            return cloneEntity;
        } else {
            //将数据在日志中输出
            LOG.error("XCEC 同步状态到crm失败:记录日志：" + JsonUtils.toJsonString(parameters));
			workOrderSynchro.setFailReason("之前状态同步失败");
			workOrderSynchro.setSyncStatus(0);
            // 配置响应实体 message、status数据
            CRMResponeEntity responeEntity = new CRMResponeEntity();
            responeEntity.setMessage("工单状态重传失败");
            responeEntity.setStatus(-1);
            responeEntity.setData(new JSONObject());
            return responeEntity;
        }

    }

	/**
	 * 将ocr识别的数据同步给sf
	 * @param map
	 */

	public void putOcrParam(Map<String, Object> map){
		String orderNo = MapUtils.getString(map, "orderNo");
		if (StringUtils.isNotBlank(orderNo)) {
			WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(orderNo);
			if (null != workOrderT && workOrderT.getOrderChannel() == 3) {// DCEC
				//将ocr 识别的数据同步给crn
				map.put("purchaseData",StringUtils.isNotBlank(workOrderT.getWarrantyStartDate())?workOrderT.getWarrantyStartDate():"");
				map.put("oemNo",StringUtils.isNotBlank(workOrderT.getoEMName())?workOrderT.getoEMName():"");
				map.put("deviceNo",StringUtils.isNotBlank(workOrderT.getVIN())?workOrderT.getVIN():"");
				map.put("chassisNo",StringUtils.isNotBlank(workOrderT.getChassisNumber())?workOrderT.getChassisNumber():"");
			}
		}

	}

	/**
	 *  同步工单状态
	 * @param channalName 服务渠道（DCEC、XCEC、BFCEC、CCI） <br>
	 * @param serviceDao
	 * @param redisClientUtils
	 * @param parameters
	 * @return
	 */
	@Override
	public CRMResponeEntity syncOrderStatusToCrm(String channalName, CRMPlatformServiceDao serviceDao, RedisClientUtils redisClientUtils, Map<String, Object> parameters,Long synchroId) {
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		WorkOrderSynchroT workOrderSynchro = new WorkOrderSynchroT();
		int synchroCount = 1;
		String appOrderNo = parameters.get("orderNo").toString();
		try {
			/**
			 * 3、判断渠道
			 **/
			if (channalName.equals(CRMServiceConst.DCEC) || channalName.equals(CRMServiceConst.DCEC_TEST)) {

				// 请求Param参数
				this.addInterfaceNullParameters("syncOrderStatusToCrm", parameters);
				//将ocr识别的结果同步给sf
				this.putOcrParam(parameters);
				// 判断如果是服务经理选择"用户不需要维修"，则关闭工单
				if ("3".equals(parameters.get("billStatus").toString())) { // 服务经理审核不通过
					if (parameters.containsKey("refuseType") && "2".equals(parameters.get("refuseType"))) {// 用户不需要维修
						parameters.put("billStatus", 15);
					}
				}
				double positionLat = MapUtils.getDoubleValue(parameters, "positionLat", 0.0);
				double positionLon = MapUtils.getDoubleValue(parameters, "positionLon", 0.0);
				if (positionLat < 60) { // APP操作同步，非重传，参数需要座处理
					parameters.put("positionLat", positionLon);
					parameters.put("positionLon", positionLat);
				}
				if (!parameters.containsKey("CRMNo") || parameters.get("CRMNo").equals("")) {
					String CRMNo = serviceDao.getCRMOrderNoByAPPOrderNo(parameters.get("orderNo").toString());
					if (CRMNo != null && CRMNo.length() > 0) {
						parameters.put("CRMNo", CRMNo);
					}
				}
				// JSONObject jsonBodyParameter = JSONObject.fromObject(parameters);
				com.alibaba.fastjson.JSONObject jsonBodyParameter = com.alibaba.fastjson.JSONObject
						.parseObject(com.alibaba.fastjson.JSON.toJSONString(parameters));

				// 请求body参数
				Map<String, Object> requestParameter = new HashMap<String, Object>();
				requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, CRMServiceConst.SYNC_ORDERSTATUS_TOCRM);
				requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBodyParameter.toString());

				// DCEC获取token及host
				Map<String, Object> map = getDCECSfTokenAndHost();
				if (MapUtils.isEmpty(map)) {
					LOG.info("DCEC 同步状态到crm 获取token失败" + JsonUtils.toJsonString(parameters));
					workOrderSynchro.setFailReason("获取token失败");
					workOrderSynchro.setSyncStatus(0);
					responeEntity = this.getNullTokenResponeEntity();
				} else {
					Map<String, Object> headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(map, "token"));
					// 判断是否redisClientUtils为空，如果为空则是异常状态重传，异常数据重传不需要保存当前状态
					Boolean syncSuccess = true;
					if (null == synchroId) {
						syncSuccess = syncOrderStatusException(redisClientUtils, serviceDao, channalName, appOrderNo, synchroId);
					}
					if (syncSuccess && null != redisClientUtils) {
						String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.SYNC_ORDERSTATUS_TOCRM;
						LOG.info("DCEC开始同步到CRM系统参数信息：" + JsonUtils.toJsonString(parameters) + "请求头信息："
								+ JsonUtils.toJsonString(headerParameter));
						JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
								MapUtils.getString(map, "token"), jsonBodyParameter.toJSONString());
						/**
						 * 4、服务器异常/超时/关闭，需要保存到redis数据库
						 **/
						if (isSaveWorkOrder(responseDate)) {
							workOrderSynchro.setFailReason(null != responseDate ? responseDate.toString().replaceAll("、","") : "返回值空");
							workOrderSynchro.setSyncStatus(0);
							Integer billStatus = MapUtils.getInteger(parameters, "billStatus");
							int status = responseDate.getInt("status");
							if(billStatus != null && billStatus==16 && status==-999){  //-999 为  当前工单下存在未取消的调件申请无法进行异常关闭，如有疑问可联系客服400-8809119
								workOrderSynchro.setSyncStatus(1);
							}
						} else {
							workOrderSynchro.setSyncStatus(1);
						}
						// 将响应消息转换成响应实体类
						responeEntity = this.getResponeEntity(responseDate, "数据同步成功");
					} else if (syncSuccess && null == redisClientUtils) {
						String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.SYNC_ORDERALLSTATUS_TOCRM;
						LOG.info("DCEC开始重传全量同步到CRM系统参数信息：" + JsonUtils.toJsonString(parameters) + "请求头信息："
								+ JsonUtils.toJsonString(headerParameter));
						JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
								MapUtils.getString(map, "token"), jsonBodyParameter.toJSONString());
						/**
						 * 4、服务器异常/超时/关闭，需要保存到redis数据库
						 **/
						if (isSaveWorkOrder(responseDate)) {
							workOrderSynchro.setFailReason(null != responseDate ? responseDate.toString().replaceAll("、","") : "返回值空");
							workOrderSynchro.setSyncStatus(0);
							Integer billStatus = MapUtils.getInteger(parameters, "billStatus");
							int status = responseDate.getInt("status");
							if(billStatus != null && billStatus==16 && status==-999){
								workOrderSynchro.setSyncStatus(1);
							}
						} else {
							workOrderSynchro.setSyncStatus(1);
						}
						// 将响应消息转换成响应实体类
						responeEntity = this.getResponeEntity(responseDate, "数据同步成功");
					} else {
						//将数据在日志中输出
						LOG.error("DCEC 同步状态到crm失败:记录日志：" + JsonUtils.toJsonString(parameters));
						workOrderSynchro.setFailReason("之前状态同步失败");
						workOrderSynchro.setSyncStatus(0);
						// 配置响应实体 message、status数据
						responeEntity = new CRMResponeEntity();
						responeEntity.setMessage("工单状态重传失败");
						responeEntity.setStatus(-1);
						responeEntity.setData(new JSONObject());
					}
				}
			} else if (channalName.equals(CRMServiceConst.XCEC) || channalName.equals(CRMServiceConst.XCEC_TEST)) {

				responeEntity = this.syncOrderStatusToCrmXcec(channalName, serviceDao, redisClientUtils, parameters, workOrderSynchro, synchroId);
			} else if (channalName.equals(CRMServiceConst.BFCEC) || channalName.equals(CRMServiceConst.BFCEC_TEST)) {

			} else if (channalName.equals(CRMServiceConst.DBU) || channalName.equals(CRMServiceConst.DBU_TEST)) {
				/**
				 * 3.2、CCI请求处理逻辑
				 */

				parameters.put("appAppraise", MapUtils.getIntValue(parameters, "appAppraise", 1));
				parameters.put("refuseReason", MapUtils.getString(parameters, "refuseReason", ""));
				parameters.put("secondLevelStationCode", MapUtils.getString(parameters, "secondLevelStationCode", ""));
				parameters.put("OrderStatus", parameters.get("billStatus"));
				parameters.put("timeOutReason", "");
				parameters.put("lackOfParts", new ArrayList<>());
				double positionLat = MapUtils.getDoubleValue(parameters, "positionLat", 0.0);
				double positionLon = MapUtils.getDoubleValue(parameters, "positionLon", 0.0);
				parameters.put("positionLat", positionLat);
				parameters.put("positionLon", positionLon);

				Map<String, Object> orderOverTime = serviceDao.getWorkOrderOverTimeInfo(parameters);
				this.addLackOfParts(orderOverTime, parameters);// 添加确实工单确实零件逻辑

				if (parameters.containsKey("billStatus")) {
					if (parameters.get("billStatus").toString().equals("18")) {// 待区域工程师处理
						parameters.put("billStatus", 2);
					} else if (parameters.get("billStatus").toString().equals("19")) {
						parameters.put("billStatus", 3);
					}
				}

				if(!parameters.containsKey("CRMNo") || parameters.get("CRMNo").equals("")){
					String crmNo = serviceDao.getCRMOrderNoByAPPOrderNo(parameters.get("orderNo").toString());
					if (crmNo != null && crmNo.length() > 0) {
						parameters.put("CRMNo", crmNo);
					} else {
						parameters.put("CRMNo", "");
					}
				}

				/**
				 * 开发DBU微信公众号 同步工单状态时增加了如下字段 工单结束时（状态为服务完成，已取消，异常关闭），需要将工单的位置信息同步给CRM。
				 */
				parameters.put("faultLat", MapUtils.getFloat(parameters, "faultLat", 0f));
				parameters.put("faultLon", MapUtils.getFloat(parameters, "faultLon", 0f));
				parameters.put("faultLocation", MapUtils.getString(parameters, "faultLocation", ""));
				parameters.put("locationIsUpdated", MapUtils.getInteger(parameters, "locationIsUpdated", 0));
				parameters.put("faultProvince", MapUtils.getString(parameters, "faultProvince", ""));
				parameters.put("faultCity", MapUtils.getString(parameters, "faultCity", ""));

				LOG.info("DUB同步服务工单状态到CRM：" + parameters);
				// 打印参数信息
				System.out.println(JsonUtils.toJsonString(parameters));

				// 添加加密请求头
				Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
				if (tokenAndHostMap == null || tokenAndHostMap.isEmpty()) {
					LOG.info("DBU 同步状态到crm 获取token失败" + JsonUtils.toJsonString(parameters));
					workOrderSynchro.setFailReason("获取token失败");
					workOrderSynchro.setSyncStatus(0);
					responeEntity = this.getNullTokenResponeEntity();
				} else {
					// 添加token请求头
					Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
					// 调取请求
					String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
							+ CRMServiceConst.SYNC_ORDERSTATUS_TOCRM;
					LOG.info("DBU同步到CRM系统参数信息：" + JsonUtils.toJsonString(parameters) + "请求头信息："
							+ JsonUtils.toJsonString(headerParameter));
					JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameters);
					/**
					 * 4、服务器异常/超时/关闭，需要保存到redis数据库
					 **/
					if (isSaveWorkOrderWithDBU(responseDate)) {
						workOrderSynchro.setFailReason(null != responseDate ? responseDate.toString() : "返回值空");
						workOrderSynchro.setSyncStatus(0);
					} else {
						workOrderSynchro.setSyncStatus(1);
					}
					// 将响应消息转换成响应实体类
					responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
				}
			} else if (channalName.equals(CRMServiceConst.CCEC)) {

				parameters.put("auditResult", MapUtils.getInteger(parameters, "auditResult", -1));
				parameters.put("rejectedReason", MapUtils.getString(parameters, "rejectedReason", ""));

				// return getSuccessEntity("屏蔽CRM代码");
				String orderNo = MapUtils.getString(parameters, "orderNo");
				Map<String, Object> dataWorkOrder = serviceDao.getOldOrderInfoByOrderNo(orderNo);
				// 非保修类服务，不通知CRM
				String requestType = MapUtils.getString(dataWorkOrder, "RequestType");
				if (StringUtils.isNotBlank(requestType) && requestType.equals("2")) {
					return getSuccessEntity("CCEC非保修类服务工单状态不通知CRM");
				}

				// 添加技师手机串号字段 2.8.0需求
				parameters.put("imei", MapUtils.getString(parameters, "imei", ""));
				Boolean retry = MapUtils.getBoolean(parameters, "retry", Boolean.FALSE);
				// APP操作同步，非重传，参数需要处理
				if (!retry) {
					parameters.put("serviceChannel", channalName);
					// 请求Param参数
					this.addInterfaceNullParameters("syncOrderStatusToCrm", parameters);
					// 判断如果是服务经理选择"用户不需要维修"，则关闭工单
					String status = MapUtils.getString(parameters, "billStatus");
					if (status.equals("3")) { // 服务经理审核不通过
						String refuseType = MapUtils.getString(parameters, "refuseType");
						if ("2".equals(refuseType)) {
							// 用户不需要维修
							parameters.put("billStatus", 15);
						}
					}
					parameters.put("positionLat", MapUtils.getDoubleValue(parameters, "positionLat", 0.0));
					parameters.put("positionLon", MapUtils.getDoubleValue(parameters, "positionLon", 0.0));
				}

				// 拼装crmNo
				String crmNo = MapUtils.getString(parameters, "CCSSComplainerOrderNo");
				if (StringUtils.isEmpty(crmNo)) {
					parameters.put("CCSSComplainerOrderNo", MapUtils.getString(dataWorkOrder, "OrderNoCrm", ""));
					parameters.put("CCSSOrderNo", MapUtils.getString(dataWorkOrder, "CCSSOrderNo", ""));
				}

				String jsonBody = JsonUtils.toJsonString(parameters);

				// 请求body参数
				Map<String, Object> requestParameter = new HashMap<>();
				requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncAppWorkOrderStatus");
				requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBody);

				// 添加加密请求头
				Map<String, Object> headerParameter = this.addEncryptionHeader(requestParameter);
				// 调取请求
				String channelHost = this.getChannelHostByChannelName(channalName);

				if (!retry) {
					// 非重试，先处理原有异常
					Boolean retrySuccess = retryExceptionSync(orderNo);
					if (!retrySuccess) {
						// 原有异常未成功，将该请求放入redis队列
						saveExceptionSyncToRedis(channalName, CRMServiceConst.SYNC_ORDER_STATUS, orderNo, parameters);
						return getErrorEntity("工单状态重传失败", null);
					} else {
						LOG.info("CCEC开始同步到CRM系统参数信息：" + JsonUtils.toJsonString(parameters) + "请求头信息："
								+ JsonUtils.toJsonString(headerParameter));
						// 重试成功，进行新请求
						JSONObject responseData = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter,
								requestParameter);
						if (isExceptionResponse(responseData)) {
							saveExceptionSyncToRedis(channalName, CRMServiceConst.SYNC_ORDER_STATUS, orderNo, parameters);
							return this.getResponeEntity(responseData, "数据同步失败");
						} else {
							String ccssOrderNo = MapUtils.getString(dataWorkOrder, "CCSSOrderNo", "");
							// 如果CCES工单编号为空，尝试查看请求结果中是否返回了相关数据
							if (StringUtils.isEmpty(ccssOrderNo)) {
								if (responseData.containsKey("data")) {
									JSONObject data = responseData.getJSONObject("data");
									if (data.containsKey("CCSSOrderNo")) {
										ccssOrderNo = data.getString("CCSSOrderNo");
										if (StringUtils.isNotEmpty(ccssOrderNo)) {
											Map<String, Object> updateMap = new HashMap<>(2);
											updateMap.put("CCSSOrderNo", ccssOrderNo);
											updateMap.put("ID", MapUtils.getLong(dataWorkOrder, "ID", 0L));
											workOrderTDao.updateByPrimaryKeySelective(updateMap);
										}
									}
								}
							}
							return this.getResponeEntity(responseData, "数据同步成功");
						}
					}
				} else {
					// 重试逻辑
					// 直接发起请求
					JSONObject responseData = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter,
							requestParameter);
					// 如果是正常响应，尝试处理CCSS工单编号
					if (!isExceptionResponse(responseData)) {
						String ccssOrderNo = MapUtils.getString(dataWorkOrder, "CCSSOrderNo", "");
						// 如果CCES工单编号为空，尝试查看请求结果中是否返回了相关数据
						if (StringUtils.isEmpty(ccssOrderNo)) {
							if (responseData.containsKey("data")) {
								JSONObject data = responseData.getJSONObject("data");
								if (null != data && data.containsKey("CCSSOrderNo")) {
									ccssOrderNo = data.getString("CCSSOrderNo");
									if (StringUtils.isNotEmpty(ccssOrderNo)) {
										Map<String, Object> updateMap = new HashMap<>(2);
										updateMap.put("CCSSOrderNo", ccssOrderNo);
										updateMap.put("ID", MapUtils.getLong(dataWorkOrder, "ID", 0L));
										workOrderTDao.updateByPrimaryKeySelective(updateMap);
									}
								}
							}
						}
					}
					return this.getResponeEntity(responseData, "数据重试");
				}
			}
		} catch (Exception e){
			LOG.error(e.getMessage(), e);
		} finally {
			Integer billStatus = MapUtils.getInteger(parameters, "billStatus");
			workOrderSynchro.setOrderNo(appOrderNo);
			workOrderSynchro.setChannelName(channalName);
			workOrderSynchro.setProcessStatus(billStatus);
			workOrderSynchro.setOrderInfo(JSON.toJSONString(parameters));
			if(null != synchroId){
				WorkOrderSynchroT synchroT = workOrderSynchroService.selectById(synchroId);
				if(null != synchroT){
					synchroCount = synchroT.getSynchroCount();
				}
				workOrderSynchro.setSynchroCount(synchroCount + 1);
				workOrderSynchro.setId(synchroId);
				workOrderSynchroService.updateById(workOrderSynchro);
			} else {
				workOrderSynchroService.add(workOrderSynchro);
			}
			//发送邮件通知
			if(workOrderSynchro.getSyncStatus() == 0 && synchroCount < 3){
				MailUtilException.sendMail("工单号：" + appOrderNo + "同步状态" + billStatus + "失败", "失败原因:" + workOrderSynchro.getFailReason(), channalName);
			}
		}
		return responeEntity;
	}

	@Override
	public CRMResponeEntity relyOrderStatusToCrm(String channalName, CRMPlatformServiceDao serviceDao,
			RedisClientUtils redisClientUtils, Map<String, Object> parameters) {
		if (channalName.equals(CRMServiceConst.CCEC)) {
			// return getSuccessEntity("屏蔽CRM代码");
			String orderNo = MapUtils.getString(parameters, "orderNo");
			Map<String, Object> dataWorkOrder = serviceDao.getOldOrderInfoByOrderNo(orderNo);
			// 非保修类服务，不通知CRM
			String requestType = MapUtils.getString(dataWorkOrder, "RequestType");
			if (StringUtils.isNotBlank(requestType) && requestType.equals("2")) {
				return getSuccessEntity("CCEC非保修类服务工单状态不通知CRM");
			}

			retryExceptionSync(orderNo);

			// 请求Param参数
			this.addInterfaceNullParameters("syncOrderStatusToCrm", parameters);
			// 判断如果是服务经理选择"用户不需要维修"，则关闭工单
			String status = MapUtils.getString(parameters, "billStatus");
			if (status.equals("3")) { // 服务经理审核不通过
				String refuseType = MapUtils.getString(parameters, "refuseType");
				if ("2".equals(refuseType)) {
					// 用户不需要维修
					parameters.put("billStatus", 15);
				}
			}
			parameters.put("positionLat", MapUtils.getDoubleValue(parameters, "positionLat", 0.0));
			parameters.put("positionLon", MapUtils.getDoubleValue(parameters, "positionLon", 0.0));

			// 拼装crmNo
			String crmNo = MapUtils.getString(parameters, "CCSSComplainerOrderNo");
			if (StringUtils.isEmpty(crmNo)) {
				parameters.put("CCSSComplainerOrderNo", MapUtils.getString(dataWorkOrder, "OrderNoCrm", ""));
				parameters.put("CCSSOrderNo", MapUtils.getString(dataWorkOrder, "CCSSOrderNo", ""));
			}
			parameters.put("imei", MapUtils.getString(parameters, "imei", ""));
			String jsonBody = JsonUtils.toJsonString(parameters);
			// 请求body参数
			Map<String, Object> requestParameter = new HashMap<>();
			requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncAppWorkOrderStatus");
			requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBody);

			// 添加加密请求头
			Map<String, Object> headerParameter = this.addEncryptionHeader(requestParameter);
			// 调取请求
			String channelHost = this.getChannelHostByChannelName(channalName);
			JSONObject responseData = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
			if (isSaveWorkOrder(responseData)) {
				getErrorEntity("同步CRM出现错误", null);
			} else {
				String ccssOrderNo = MapUtils.getString(dataWorkOrder, "CCSSOrderNo", "");
				// 如果CCES工单编号为空，尝试查看请求结果中是否返回了相关数据
				if (StringUtils.isEmpty(ccssOrderNo)) {
					if (responseData.containsKey("data")) {
						JSONObject data = responseData.getJSONObject("data");
						if (data.containsKey("CCSSOrderNo")) {
							ccssOrderNo = data.getString("CCSSOrderNo");
							if (StringUtils.isNotEmpty(ccssOrderNo)) {
								Map<String, Object> updateMap = new HashMap<>(2);
								updateMap.put("CCSSOrderNo", ccssOrderNo);
								updateMap.put("ID", MapUtils.getLong(dataWorkOrder, "ID", 0L));
								serviceDao.updateWorkOrderInfo(updateMap);
							}
						}
					}
				}
				// 将响应消息转换成响应实体类
				return this.getResponeEntity(responseData, "数据同步成功");
			}
		}
		return getErrorEntity("未知渠道信息" + channalName, null);
	}

	@Override
	public CRMResponeEntity syncUserAppraisalInfoToCrm(String channalName, CRMPlatformServiceDao serviceDao,
			RedisClientUtils redisClientUtils, Map<String, Object> parameters) {
		/**
		 * 1、初始化响应实体
		 */
		CRMResponeEntity verfyRespone = this.verifyParameters(channalName);
		if (verfyRespone.getStatus() == CRMServiceConst.CHANNEL_VERIFY_FAILURE) {
			return verfyRespone;
		}
		/**
		 * 3、判断渠道
		 **/
		if (channalName.equals(CRMServiceConst.DCEC) || channalName.equals(CRMServiceConst.DCEC_TEST)) {
			// 请求Param参数
			this.addInterfaceNullParameters("syncUserAppraisalInfoToCrm", parameters);
			// 请求Param参数
			JSONObject jsonBodyParameter = JSONObject.fromObject(parameters);
			// 请求body参数
			Map<String, Object> requestParameter = new HashMap<String, Object>();
			requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, CRMServiceConst.SYNC_USERAPPRAISALINFO_TOCRM);
			requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBodyParameter.toString());
			// DCEC获取token及host
			Map<String, Object> map = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(map)){
				LOG.info("DCEC 同步信息到crm 获取token失败" + JsonUtils.toJsonString(parameters));
				this.saveWorkOrderInfoToRedis(redisClientUtils, CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP,
						channalName, parameters);
				return this.getNullTokenResponeEntity();
			}
			Map<String, Object> headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(map, "token"));
			String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.SYNC_USERAPPRAISALINFO_TOCRM;

			List<Map<String, Object>> list = new ArrayList<>();
			list.add(parameters);

			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
					MapUtils.getString(map, "token"), JsonUtils.toJsonString(list));
			// 服务器异常/超时/关闭，需要保存到redis数据库
			if (isSaveWorkOrder(responseDate)) {
				this.saveWorkOrderInfoToRedis(redisClientUtils, CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP,
						channalName, parameters);
			}
			// 将响应消息转换成响应实体类
			return this.getResponeEntity(responseDate, "同步用户评价信息成功");

		} else if (channalName.equals(CRMServiceConst.XCEC) || channalName.equals(CRMServiceConst.XCEC_TEST)) {
			/**
			 * 3.2、XCEC请求处理逻辑
			 */
			// 请求Param参数
			this.addInterfaceNullParameters("syncUserAppraisalInfoToCrm", parameters);
			System.out.println(JsonUtils.toJsonString(parameters));
			// 添加加密请求头
			Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
			if (tokenAndHostMap == null) {
				return this.getNullTokenResponeEntity();
			}
			// 添加token请求头
			Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);
			// 调取请求
			String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
					+ CRMServiceConst.SYNC_USERAPPRAISALINFO_TOCRM;
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameters);
			// 服务器异常/超时/关闭，需要保存到redis数据库
			if (isSaveWorkOrderWithXCEC(responseDate)) {
				this.saveWorkOrderInfoToRedis(redisClientUtils, CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP,
						channalName, parameters);
			}
			// 将响应消息转换成响应实体类
			CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
			// 将响应消息转换成响应实体类
			return responeEntity;
		} else if (channalName.equals(CRMServiceConst.BFCEC) || channalName.equals(CRMServiceConst.BFCEC_TEST)) {

		} else if (channalName.equals(CRMServiceConst.DBU) || channalName.equals(CRMServiceConst.DBU_TEST)) {

			/**
			 * 3.2、CCI请求处理逻辑
			 */
			String CRMNo = serviceDao.getCRMOrderNoByAPPOrderNo(parameters.get("orderNo").toString());
			if (CRMNo != null && CRMNo.length() > 0) {
				parameters.put("crmNo", CRMNo);
			} else {
				parameters.put("crmNo", "");
			}
			// 添加加密请求头
			Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
			// 添加token请求头
			Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
			// 调取请求
			String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
					+ CRMServiceConst.SYNC_USERAPPRAISALINFO_TOCRM;
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameters);
			// 服务器异常/超时/关闭，需要保存到redis数据库
			if (isSaveWorkOrderWithDBU(responseDate)) {
				this.saveWorkOrderInfoToRedis(redisClientUtils, CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP,
						channalName, parameters);
			}
			// 将响应消息转换成响应实体类
			CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
			// 将响应消息转换成响应实体类
			return responeEntity;
		} else if (CRMServiceConst.CCEC.equals(channalName)) {

			// return getSuccessEntity("屏蔽CRM代码");
			Map<String, Object> requestParameter = new HashMap<>();
			requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncUserAppraise");
			requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, JsonUtils.toJsonString(parameters));
			// 添加加密请求头
			Map<String, Object> headerParameter = this.addEncryptionHeader(requestParameter);
			// 调取请求
			String channelHost = this.getChannelHostByChannelName(channalName);
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
			// 服务器异常/超时/关闭，需要保存到redis数据库
			if (isSaveWorkOrder(responseDate)) {
				this.saveWorkOrderInfoToRedis(redisClientUtils, CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP,
						channalName, parameters);
			}
			// 将响应消息转换成响应实体类
			return this.getResponeEntity(responseDate, "同步用户评价信息成功");
		}

		return null;

	}

	// ljk 2.2.6 APP系统同步自行诊断信息到CRM系统
	@Override
	public CRMResponeEntity activeDiagnostics(String channalName, Map<String, Object> parameters,
			RedisClientUtils redisClientUtils) {

		if (redisClientUtils != null) { // APP操作，非重传
			if (parameters.containsKey("renewalParts") && parameters.get("renewalParts").toString().length() > 0) {
				List<Map<String, Object>> renewalPartList = this
						.addRenewalParts(parameters.get("renewalParts").toString());
				parameters.put("renewalParts", renewalPartList);
			} else {
				parameters.put("renewalParts", new ArrayList<>());
			}
		}

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_ACTIVEDIAGNOSTICS_TOCRM;
		JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameters);
		// 服务器异常/超时/关闭，需要保存到redis数据库
		if (isSaveWorkOrderWithDBU(responseDate)) {
			this.saveWorkOrderInfoToRedis(redisClientUtils, CRMServiceConst.KEY_ORDERACTIVE_DIAGNOSTICS_EXCEPTIONAL_APP,
					channalName, parameters);
		}
		// 将响应消息转换成响应实体类
		CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
		// 将响应消息转换成响应实体类
		return responeEntity;
	}

	// ljk 2.2.7 APP系统同步诊断维修结论信息到CRM系统
	@Override
	public CRMResponeEntity drConclusion(String channalName, Map<String, Object> parameters,
			RedisClientUtils redisClientUtils) {

		if (redisClientUtils != null) { // APP操作，非重传
			int failureMode = MapUtils.getIntValue(parameters, "failureMode", 0);
			CRMPlatformServiceDao serviceDao = (CRMPlatformServiceDao) ApplicationContextUtils
					.getBean("CRMPlatformServiceDao");
			Map<String, Object> failureModeMap = serviceDao.getFailureModeCode(failureMode);
			parameters.put("failureMode", MapUtils.getString(failureModeMap, "Remark", ""));
		}

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_DRCONCLUSION_TOCRM;
		JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameters);
		// 服务器异常/超时/关闭，需要保存到redis数据库
		if (isSaveWorkOrderWithDBU(responseDate)) {
			this.saveWorkOrderInfoToRedis(redisClientUtils, CRMServiceConst.KEY_DR_CONCLUSION_EXCEPTIONAL_APP,
					channalName, parameters);
		}
		// 将响应消息转换成响应实体类
		CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
		// 将响应消息转换成响应实体类
		return responeEntity;
	}

	// 2.2.5 APP系统同步工单照片信息到CRM系统
	@Override
	public CRMResponeEntity syncWorkOrderPics(String channalName, Map<String, Object> picMap,
			RedisClientUtils redisClientUtils) {

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "") + CRMServiceConst.SYNC_WORKORDERPICS;
		JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, picMap);
		// 将响应消息转换成响应实体类
		CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
		// 将响应消息转换成响应实体类
		return responeEntity;
	}

	// 2.1.3 APP系统同步服务站人员信息到CRM系统
	@Override
	public CRMResponeEntity syncServiceStationUser(String channalName,
			List<Map<String, Object>> serviceTechnicianMsgList) {
		// 添加加密请求头
		// 添加token请求头
		Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
		String tokenStr = MapUtils.getString(tokenAndHostMap, "token", "");
		Header auth = new BasicHeader("Authorization", tokenStr);
		// 调取请求
		LOG.info("同步服务站技师信息到CRM系统参数信息：" + JsonUtils.toJsonString(serviceTechnicianMsgList));
		// https://cumminsxian--TEST.cs58.my.salesforce.com/services/apexrest/WebAPIService/syncStationUserInfo
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "") + "WebAPIService/"
				+ CRMServiceConst.CRMSYNCSTATIONUSERINFO_TOAPP;
		String respones = HttpUtils.postJson(channelHost, JsonUtils.toJsonString(serviceTechnicianMsgList),
				new ResponseHandler<String>() {
					@Override
					public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
						if (response.getStatusLine().getStatusCode() == 200) {
							HttpEntity httpEntity = response.getEntity();
							return EntityUtils.toString(httpEntity, "UTF-8");
						}
						return null;
					}
				}, auth);
		// 将String数组转为JSON
		JSONObject responseBody = JSONObject.fromObject(respones);
		// 将响应消息转换成响应实体类
		CRMResponeEntity responeEntity = this.getResponeEntity(responseBody, "数据获取成功");
		// 将响应消息转换成响应实体类
		return responeEntity;
	}

	@Override
	public CRMResponeEntity syncTimeoutAccomplish(String channelName, Map<String, Object> map) {
		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_TIMEOUTACCOMPLISH;
		JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);
		// 将响应消息转换成响应实体类
		CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
		// 将响应消息转换成响应实体类
		return responeEntity;
	}

	@Override
	public CRMResponeEntity syncTroubleshootingSummary(String channelName, Map<String, Object> map) {
		try {
			// return getSuccessEntity("屏蔽CRM代码");
			String orderNo = MapUtils.getString(map, "orderNo");
			Map<String, Object> dataWorkOrder = crmPlatformServiceDao.getOldOrderInfoByOrderNo(orderNo);
			// 非保修类服务，不通知CRM
			String requestType = MapUtils.getString(dataWorkOrder, "RequestType");
			if (StringUtils.isNotBlank(requestType) && requestType.equals("2")) {
				return getSuccessEntity("非保修工单不需同步");
			}

			Map<String, Object> requestParameter = new HashMap<>();
			requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "drConclusionInfo");
			requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, JsonUtils.toJsonString(map));

			Map<String, Object> headerParameter = new HashMap<>();
			String channelHost = "";
			if (channelName.equals(CRMServiceConst.DCEC)) {
				Map<String, Object> tokenAndHost = getDCECSfTokenAndHost();
				if(MapUtils.isEmpty(tokenAndHost)){
					saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_TROUBLE_SHOOTING_SUMMARY, orderNo, map);
					return this.getNullTokenResponeEntity();
				}
				// 添加加密请求头
				headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(tokenAndHost, "token"));
				// 调取请求
				channelHost = MapUtils.getString(tokenAndHost, "hostUrl") + "drConclusionInfo";
			} else {
				// 添加加密请求头
				headerParameter = this.addEncryptionHeader(requestParameter);
				// 调取请求
				channelHost = this.getChannelHostByChannelName(channelName);
			}

			Boolean retry = MapUtils.getBoolean(map, "retry", Boolean.FALSE);
			JSONObject responseDate = null;
			if (!retry) {
				// 非重传，先重试之前异常的
				Boolean retrySuccess = retryExceptionSync(orderNo);
				if (!retrySuccess) {
					// 重试没成功
					saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_TROUBLE_SHOOTING_SUMMARY, orderNo, map);
					return getErrorEntity("工单异常重传失败", null);
				}
				// 发起请求
				responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
				// 将响应消息转换成响应实体类
				if (isExceptionResponse(responseDate)) {
					LOG.error("同步故障排除总结通知存在问题，" + JsonUtils.toJsonString(responseDate));
					saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_TROUBLE_SHOOTING_SUMMARY, orderNo, map);
				}
			} else {
				// 重传
				responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
			}
			return this.getResponeEntity(responseDate, "数据获取成功");
		} catch (Exception e) {
			LOG.error("同步故障排除总结通知发生异常，" + e.getMessage(), e);
		}
		return getErrorEntity("同步故障排除总结通知发生异常", null);
	}

	@Override
	public CRMResponeEntity syncWorkOrderAffirm(String channelName, Map<String, Object> map) {
		// return getSuccessEntity("屏蔽CRM代码");
		String orderNo = MapUtils.getString(map, "orderNo");
		Map<String, Object> dataWorkOrder = crmPlatformServiceDao.getOldOrderInfoByOrderNo(orderNo);
		// 非保修类服务，不通知CRM
		String requestType = MapUtils.getString(dataWorkOrder, "RequestType");
		if (StringUtils.isNotBlank(requestType) && requestType.equals("2")) {
			return getSuccessEntity("非保修工单不需同步");
		}

		Map<String, Object> requestParameter = new HashMap<>();
		requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncWorkOrderAffirm");
		requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, JsonUtils.toJsonString(map));
		Map<String, Object> headerParameter = new HashMap<>();
		String channelHost = "";
		if (channelName.equals(CRMServiceConst.DCEC)) {
			Map<String, Object> tokenAndHost = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(tokenAndHost)){
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_ORDER_AFFIRM, orderNo, map);
				return this.getNullTokenResponeEntity();
			}
			// 添加加密请求头
			headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(tokenAndHost, "token"));
			// 调取请求
			channelHost = MapUtils.getString(tokenAndHost, "hostUrl") + "syncWorkOrderAffirm";
		} else {
			// 添加加密请求头
			headerParameter = this.addEncryptionHeader(requestParameter);
			// 调取请求
			channelHost = this.getChannelHostByChannelName(channelName);
		}

		Boolean retry = MapUtils.getBoolean(map, "retry", Boolean.FALSE);
		JSONObject responseDate = null;
		if (!retry) {
			Boolean retrySuccess = retryExceptionSync(orderNo);
			if (!retrySuccess) {
				// 重试没成功
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_ORDER_AFFIRM, orderNo, map);
				return getErrorEntity("工单异常重传失败", null);
			}
			responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
			if (isExceptionResponse(responseDate)) {
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_ORDER_AFFIRM, orderNo, map);
			}
		} else {
			responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
		}

		return this.getResponeEntity(responseDate, "数据获取成功");
	}

	@Override
	public CRMResponeEntity syncConfirmationRepair(String channelName, Map<String, Object> map) {
		// return getSuccessEntity("屏蔽CRM代码");
		String orderNo = MapUtils.getString(map, "orderNo");
		Map<String, Object> dataWorkOrder = crmPlatformServiceDao.getOldOrderInfoByOrderNo(orderNo);
		// 非保修类服务，不通知CRM
		String requestType = MapUtils.getString(dataWorkOrder, "RequestType");
		if (StringUtils.isNotBlank(requestType) && requestType.equals("2")) {
			return getSuccessEntity("非保修工单不需同步");
		}

		Map<String, Object> requestParameter = new HashMap<>();
		requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncConfirmationRepair");
		requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, JsonUtils.toJsonString(map));
		Map<String, Object> headerParameter = new HashMap<>();
		String channelHost = "";
		if (channelName.equals(CRMServiceConst.DCEC)) {
			Map<String, Object> tokenAndHost = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(tokenAndHost)){
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_CONFIRMATION_REPAIR, orderNo, map);
				return this.getNullTokenResponeEntity();
			}
			// 添加加密请求头
			headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(tokenAndHost, "token"));
			// 调取请求
			channelHost = MapUtils.getString(tokenAndHost, "hostUrl") + "syncConfirmationRepair";
		} else {
			// 添加加密请求头
			headerParameter = this.addEncryptionHeader(requestParameter);
			// 调取请求
			channelHost = this.getChannelHostByChannelName(channelName);
		}

		Boolean retry = MapUtils.getBoolean(map, "retry", Boolean.FALSE);
		JSONObject responseDate = null;
		if (!retry) {
			Boolean retrySuccess = retryExceptionSync(orderNo);
			if (!retrySuccess) {
				// 重试没成功
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_CONFIRMATION_REPAIR, orderNo, map);
				return getErrorEntity("工单异常重传失败", null);
			}
			responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
			if (isExceptionResponse(responseDate)) {
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_CONFIRMATION_REPAIR, orderNo, map);
			}
		} else {
			responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
		}
		return this.getResponeEntity(responseDate, "数据获取成功");
	}

	@Override
	public CRMResponeEntity syncRemoteSolution(String channelName, Map<String, Object> map) {
		// return getSuccessEntity("屏蔽CRM代码");
		String orderNo = MapUtils.getString(map, "orderNo");
		Map<String, Object> dataWorkOrder = crmPlatformServiceDao.getOldOrderInfoByOrderNo(orderNo);
		// 非保修类服务，不通知CRM
		String requestType = MapUtils.getString(dataWorkOrder, "RequestType");
		if (StringUtils.isNotBlank(requestType) && requestType.equals("2")) {
			return getSuccessEntity("非保修工单不需同步");
		}

		Map<String, Object> requestParameter = new HashMap<>();
		requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, "syncRemoteSolution");
		requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, JsonUtils.toJsonString(map));
		Map<String, Object> headerParameter = new HashMap<>();
		String channelHost = "";
		if (channelName.equals(CRMServiceConst.DCEC)) {
			Map<String, Object> tokenAndHost = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(tokenAndHost)){
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_REMOTE_SOLUTION, orderNo, map);
				return this.getNullTokenResponeEntity();
			}
			// 添加加密请求头
			headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(tokenAndHost, "token"));
			// 调取请求
			channelHost = MapUtils.getString(tokenAndHost, "hostUrl") + "syncRemoteSolution";
		} else {
			// 添加加密请求头
			headerParameter = this.addEncryptionHeader(requestParameter);
			// 调取请求
			channelHost = this.getChannelHostByChannelName(channelName);
		}
		Boolean retry = MapUtils.getBoolean(map, "retry", Boolean.FALSE);
		JSONObject responseDate = null;
		if (!retry) {
			Boolean retrySuccess = retryExceptionSync(orderNo);
			if (!retrySuccess) {
				// 重试没成功
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_REMOTE_SOLUTION, orderNo, map);
				return getErrorEntity("工单异常重传失败", null);
			}
			responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
			if (isExceptionResponse(responseDate)) {
				saveExceptionSyncToRedis(channelName, CRMServiceConst.SYNC_REMOTE_SOLUTION, orderNo, map);
			}
		} else {
			responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, requestParameter);
		}
		return this.getResponeEntity(responseDate, "数据获取成功");
	}

//==================================================================================================================
	/**
	 * @return com.cci.kangdao.crmapi.CRMResponeEntity
	 * @Author Joe
	 * @Description 更具接口返回的响应消息，组装成响应实体
	 * @Date 9:55 AM 2019/3/30
	 * @Param [responseDate]
	 **/
	public CRMResponeEntity getResponeEntity(JSONObject responseDate, String message) {
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		if (null == responseDate) {
			responeEntity.setMessage("crm信息获取失败");
			responeEntity.setStatus(-1);
		} else {
			if (responseDate.containsKey("status") && responseDate.getInt("status") == 0) { // 成功

				// 配置响应实体 data数据
				if (responseDate.containsKey("data") && responseDate.get("data") != null) {
					// 判断是否data数据类型是JSON
					if (responseDate.get("data") instanceof JSONObject) {
						JSONObject jsonObject = responseDate.getJSONObject("data");
						responeEntity.setData(jsonObject);
					} else {
						responeEntity.setData(new JSONObject());
					}

				} else {
					if (responseDate.containsKey("OcrUpdateFlag"))  {
						String ocrUpdateFlag = responseDate.getString("OcrUpdateFlag");
						if (StringUtils.isNotBlank(ocrUpdateFlag)) {
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("OcrUpdateFlag",ocrUpdateFlag);
							responeEntity.setData(jsonObject);
						}
					}else {
						responeEntity.setData(new JSONObject());
					}
				}

				// 配置响应实体 message、status数据
				responeEntity.setMessage(message);
				responeEntity.setStatus(0);
			} else // 失败
			{

				// 配置响应实体 message、status数据
				if (responseDate.containsKey("msg") && responseDate.get("msg") != null) {
					responeEntity.setMessage(responseDate.get("msg").toString());
				}
				if (responseDate.containsKey("message") && responseDate.get("message") != null && StringUtils.isEmpty(responeEntity.getMessage())) {
					responeEntity.setMessage(responseDate.get("message").toString());
				}
				if (responseDate.containsKey("status") && responseDate.get("status") != null) {
					responeEntity.setStatus(Integer.valueOf(responseDate.get("status").toString()));
				} else {
					responeEntity.setStatus(-1);
				}
				if (responseDate.containsKey("data") && responseDate.get("data") != null) {
					if (responseDate.get("data") instanceof JSONObject) {
						responeEntity.setData(responseDate.getJSONObject("data"));
					} else {
						responeEntity.setData(new JSONObject());
					}

				} else {
					responeEntity.setData(new JSONObject());
				}

			}
		}
		return responeEntity;
	}

	/**
	 * @return com.cci.kangdao.crmapi.CRMResponeEntity
	 * @Author Joe
	 * @Description 更具接口返回的响应消息，组装成响应实体
	 * @Date 9:55 AM 2019/3/30
	 * @Param [responseDate]
	 **/
	public CRMResponeEntity getResponeEntityStr(JSONObject responseDate, String message) {
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		if (null == responseDate) {
			responeEntity.setMessage("crm信息获取失败");
			responeEntity.setStatus(-1);
		} else {
			if (responseDate.containsKey("status") && "success".equals(responseDate.getString("status"))) { // 成功
				// 配置响应实体 data数据
				if (responseDate.containsKey("dealerInfos") && responseDate.get("dealerInfos") != null) {
					// 判断是否data数据类型是JSON
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("data", responseDate.get("dealerInfos"));
					responeEntity.setData(jsonObject);
				} else {
					responeEntity.setData(new JSONObject());
				}

				// 配置响应实体 message、status数据
				responeEntity.setMessage(message);
				responeEntity.setStatus(0);
			} else // 失败
			{

				// 配置响应实体 message、status数据
				if (responseDate.containsKey("msg") && responseDate.get("msg") != null) {
					responeEntity.setMessage(responseDate.get("msg").toString());
				} else {
					responeEntity.setStatus(-1);
				}
				if (responseDate.containsKey("data") && responseDate.get("data") != null) {
					if (responseDate.get("data") instanceof JSONObject) {
						responeEntity.setData(responseDate.getJSONObject("data"));
					} else {
						responeEntity.setData(new JSONObject());
					}

				} else {
					responeEntity.setData(new JSONObject());
				}

			}
		}
		return responeEntity;
	}

	/**
	 * @param channelname @return @throws @author: leonbreeze @Description:
	 *                    根据服务渠道名字获取渠道host @date: Jan 24, 2019 1:23:36 PM @return:
	 *                    String @throws
	 */
	public String getChannelHostByChannelName(String channelname) {

		if (channelname.equals(CRMServiceConst.DCEC) || channelname.equals(CRMServiceConst.DCEC_TEST)) {
			Map<String, Object> map = getDCECSfTokenAndHost();
			if (map != null && map.containsKey("hostUrl") && map.get("hostUrl") != null) {
				return map.get("hostUrl").toString();
			} else {
				return "";
			}
//            return getProperties("projectconfig.properties", "crm.dcec.host").trim();
		} else if (channelname.equals(CRMServiceConst.XCEC) || channelname.equals(CRMServiceConst.XCEC_TEST)) {
			return CRMServiceConst.HOST_XCEC;
		} else if (channelname.equals(CRMServiceConst.BFCEC) || channelname.equals(CRMServiceConst.BFCEC_TEST)) {
			return CRMServiceConst.HOST_BFCEC;
		} else if (channelname.equals(CRMServiceConst.DBU) || channelname.equals(CRMServiceConst.DBU_TEST)) {
			Map<String, Object> map = getCCICrmTokenAndHost();
			if (map != null && map.containsKey("hostUrl") && map.get("hostUrl") != null) {
				return map.get("hostUrl").toString();
			} else {
				return "";
			}
		} else if (channelname.equals(CRMServiceConst.CCEC)) {
			return getProperties("projectconfig.properties", "crm.ccec.host").trim();
		}
		return "";
	}

	/**
	 * @author: leonbreeze @Description: 验证渠道名 @param channelname @return @date: Jan
	 *          24, 2019 1:40:01 PM @return: CRMResponeEntity @throws
	 */
	public CRMResponeEntity verifyParameters(String channelname) {
		CRMResponeEntity responseEntity = new CRMResponeEntity();
		String channelHost = this.getChannelHostByChannelName(channelname);
		if (channelHost.length() == 0) {
			/**
			 * 1、传递参数为空
			 */
			responseEntity.setMessage("渠道名不正确或渠道名为空");
			responseEntity.setStatus(1);
			return responseEntity;
		}
		/**
		 * 2、验证通过
		 */
		responseEntity.setStatus(0);
		return responseEntity;
	}

	/**
	 * @Author Joe
	 * @Description DCEC 添加加密头
	 * @Date 9:41 AM 2019/3/30
	 * @Param []
	 **/
	public Map<String, Object> addDCECEncryptionHeader(String token) {

		// 添加加密请求头
		Map<String, Object> headerParameter = new HashMap<String, Object>();
		// 请求头参数
//        requestParameter.put("company", CRMServiceConst.ECummins);
//        requestParameter.put("systemTime", LocalTimeUtil.getRealCurrentTime());
		headerParameter.put("Authorization", token);
		return headerParameter;
	}

	/**
	 * @return java.util.Map<java.lang.String, java.lang.Object>
	 * @Author Joe
	 * @Description CCEC 添加加密头
	 * @Date 9:41 AM 2019/3/30
	 * @Param []
	 **/
	public Map<String, Object> addEncryptionHeader(Map<String, Object> requestParameter) {

		// 添加加密请求头
		Map<String, Object> headerParameter = new HashMap<String, Object>();
		// 请求头参数
		requestParameter.put("company", CRMServiceConst.ECummins);
		requestParameter.put("systemTime", LocalTimeUtil.getRealCurrentTime());
		headerParameter.put("token", MapUtils.getString(requestParameter, "token"));
		if (CRMServiceConst.IS_CRMHEADER_ADDMD5) {
			// 请求头参数
			requestParameter.put("company", CRMServiceConst.ECummins);
			requestParameter.put("systemTime", LocalTimeUtil.getRealCurrentTime());

			String token = String.format("%s+%s", requestParameter.get("company"), requestParameter.get("systemTime"));
			headerParameter.put("token", PublicTool.compute(token));
		}
		return headerParameter;
	}

	/**
	 * @Author Joe
	 * @Description CCI添加加密头
	 * @Date 9:41 AM 2019/3/30
	 * @Param []
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 **/
	public Map<String, Object> addXCECEncryptionHeader(Map<String, Object> requestParameter) {

		// 添加加密请求头
		String tokenStr = MapUtils.getString(requestParameter, "token", "");
		Map<String, Object> headerParameter = new HashMap<String, Object>();

		headerParameter.put("Authorization", tokenStr);
		headerParameter.put("Content-Type", "XCEC");
		return headerParameter;
	}

	/**
	 * @Author Joe
	 * @Description CCI添加加密头
	 * @Date 9:41 AM 2019/3/30
	 * @Param []
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 **/
	public Map<String, Object> addCCIEncryptionHeader(Map<String, Object> requestParameter) {

		// 添加加密请求头
		String tokenStr = MapUtils.getString(requestParameter, "token", "");
		Map<String, Object> headerParameter = new HashMap<String, Object>();

		headerParameter.put("Authorization", tokenStr);
		headerParameter.put("Content-Type", "CCI");
		return headerParameter;
	}

	/**
	 * CCI根据接口添加空字段 @Title: addCCIInterfaceNullParameters @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param map @param @return @return
	 * CRMResponeEntity @throws
	 */
	public void addCCIInterfaceNullParameters(String intefaceName, Map<String, Object> map) {
		if (intefaceName.equals("syncAppOrderInfoToCRM")) {
			map.put("orderNo", MapUtils.getString(map, "orderNo", ""));
			map.put("ESN", MapUtils.getString(map, "ESN", ""));
			map.put("marketTypes", MapUtils.getString(map, "marketTypes", ""));
			map.put("applications", MapUtils.getString(map, "applications", ""));
			map.put("warrantyStartDate", MapUtils.getString(map, "warrantyStartDate", ""));
			map.put("equipmentNo", MapUtils.getString(map, "equipmentNo", ""));
			map.put("vehicleCompany", MapUtils.getString(map, "vehicleCompany", ""));
			map.put("manufactor", MapUtils.getString(map, "manufactor", ""));
			map.put("customerName", MapUtils.getString(map, "customerName", ""));
			map.put("customerPhone", MapUtils.getString(map, "customerPhone", ""));
			map.put("faultLat", MapUtils.getString(map, "faultLat", ""));
			map.put("faultLon", MapUtils.getString(map, "faultLon", ""));
			map.put("faultLocation", MapUtils.getString(map, "faultLocation", ""));

		}

	}

	/**
	 * 根据接口添加空字段 @Title: addInterfaceNullParameters @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param map @param @return @return
	 * CRMResponeEntity @throws
	 */
	public void addInterfaceNullParameters(String intefaceName, Map<String, Object> map) {
		if (intefaceName.equals("syncAppOrderInfoToCRM")) {
			String serviceChannel = MapUtils.getString(map, "serviceChannel", "");
			if (!map.containsKey("equipmentNo")) {
				map.put("equipmentNo", "");
			} else {
				String equipmentNo = MapUtils.getString(map, "equipmentNo", "");
				map.put("equipmentNo", equipmentNo);
			}
			if (!map.containsKey("serviceCar")) {
				map.put("serviceCar", "");
			} else {
				String serviceCar = MapUtils.getString(map, "serviceCar", "");
				map.put("serviceCar", serviceCar);
			}
			if (!map.containsKey("needGoOut")) {
				if (serviceChannel.equals("CCEC")) {
					map.put("needGoOut", 1);
				} else {
					map.put("needGoOut", -1);
				}
			} else {
				int needGoOut = MapUtils.getIntValue(map, "needGoOut", -1);
				map.put("needGoOut", needGoOut);
			}
			if (!map.containsKey("remark")) {
				map.put("remark", "");
			} else {
				String remark = MapUtils.getString(map, "remark", "");
				map.put("remark", remark);
			}

			if (map.containsKey("faultLat")) {
				double faultLat = MapUtils.getDoubleValue(map, "faultLat", 0.0);
				double faultLon = MapUtils.getDoubleValue(map, "faultLon", 0.0);
				map.put("faultLat", faultLon);// 因为文档写反了
				map.put("faultLon", faultLat);// 因为文档写反了
			} else {
				map.put("faultLat", 0.0);// 因为文档写反了
				map.put("faultLon", 0.0);// 因为文档写反了
			}
			map.put("workHours", MapUtils.getString(map, "workHours", ""));
			map.put("workMileages", MapUtils.getString(map, "workMileages", ""));

			map.put("stationNo", MapUtils.getString(map, "stationNo", ""));
			map.put("stationName", MapUtils.getString(map, "stationName", ""));
			// CCEC拼装
			if (serviceChannel.equals("CCEC")) {
				String repairerType = MapUtils.getString(map, "repairerType", "3");
				map.put("repairerType", repairerType);

				// CCEC处理
				String requestType = MapUtils.getString(map, "requestType", "");
				if (requestType.equals("1")) {
					map.put("requestType", "2");
				} else if (requestType.equals("2")) {
					map.put("requestType", "1");
				} else {
					map.put("requestType", "");
				}

				String goOutType = MapUtils.getString(map, "goOutType", "");
				if (goOutType.equals("1")) {
					map.put("goutMode", "2");
				} else if (goOutType.equals("2")) {
					map.put("goutMode", "3");
				} else if (goOutType.equals("3")) {
					map.put("goutMode", "1");
				} else if (goOutType.equals("4")) {
					map.put("goutMode", "0");
				} else {
					map.put("goutMode", "");
				}

				map.put("serviceInitPlan", MapUtils.getString(map, "serviceInitPlan", ""));
				map.put("orderCategory", MapUtils.getString(map, "orderCategory", ""));
				map.put("urgencyDegree", "4");
				map.put("dispatchServiceType", "0");
				map.put("factory", "OTCQ");
				map.put("approvalCategory", "1");
				map.put("orderType", "0");
				map.put("estimateWarrantyStartDate", MapUtils.getString(map, "estimateWarrantyStartDate", ""));
				map.put("faultReason", MapUtils.getString(map, "faultReason", ""));
				map.put("sizeFailure", MapUtils.getString(map, "sizeFailure", ""));
			}
		} else if (intefaceName.equals("syncOrderStatusToCrm")) {

			if (!map.containsKey("drOrderNo")) {
				map.put("drOrderNo", "");
			} else {
				String drOrderNo = MapUtils.getString(map, "drOrderNo", "");
				map.put("drOrderNo", drOrderNo);
			}

			if (!map.containsKey("drDiagnoseReport")) {
				map.put("drDiagnoseReport", "");
			} else {
				String drDiagnoseReport = MapUtils.getString(map, "drDiagnoseReport", "");
				map.put("drDiagnoseReport", drDiagnoseReport);
			}
			if (!map.containsKey("oldOrderNo")) {
				map.put("oldOrderNo", "");
			} else {
				String oldOrderNo = MapUtils.getString(map, "oldOrderNo", "");
				map.put("oldOrderNo", oldOrderNo);
			}
			if (!map.containsKey("CRMNo")) {
				map.put("CRMNo", "");
			} else {
				String CRMNo = MapUtils.getString(map, "CRMNo", "");
				map.put("CRMNo", CRMNo);
			}

			map.put("SMN", MapUtils.getString(map, "SMN", ""));
			map.put("stationNo", MapUtils.getString(map, "stationNo", ""));
			// -------------二网改造begin---------------
			// childStationNo 二网服务站编号 String 非必填项
			// stationNo 服务站编号（服务经理确认不通过，改派服务站） String 非必填项 商务处主任改判也用此字段
			// 实际开发中发现DCEC同步的时候没有传stationNo，只有ccec的时候传了。这里通过orderNo获取一网二网授权号
			if (map.containsKey("orderNo") && !StringUtils.isBlank(map.get("orderNo").toString())) {
				String orderNo = map.get("orderNo").toString();
				WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(orderNo);
				if (null != workOrderT && workOrderT.getOrderChannel() == 3) {// DCEC
					SSRepairT fatherSSRepairT = sSRepairTDao.getSSRepairTByCompanyNoAndChildServiceStationID(
							CRMServiceConst.DCEC, workOrderT.getServiceStationId());
					SSRepairT ssRepairT = sSRepairTDao.getSSRepairTByCompanyNoAndServiceStationID(CRMServiceConst.DCEC,
							workOrderT.getServiceStationId());
					if(null != ssRepairT){
						if (fatherSSRepairT == null) {
							map.put("stationNo", ssRepairT.getBusinessno());// 一网授权号
						} else {
							map.put("childStationNo", ssRepairT.getBusinessno());// 二网授权号
							map.put("stationNo", fatherSSRepairT.getBusinessno());// 一网授权号
						}
					}
				}
			}
			// -------------二网改造end---------------
			map.put("refuseReason", MapUtils.getString(map, "refuseReason", ""));
			map.put("assistEngineerName", MapUtils.getString(map, "assistEngineerName", ""));
			if (!map.containsKey("engineerPhone")) {
				map.put("engineerPhone", "");
			} else {
				String engineerPhone = MapUtils.getString(map, "engineerPhone", "");
				map.put("engineerPhone", engineerPhone);
			}
			if (!map.containsKey("phoneIMEI")) {
				map.put("phoneIMEI", "");
			} else {
				String phoneIMEI = MapUtils.getString(map, "phoneIMEI", "");
				map.put("phoneIMEI", phoneIMEI);
			}
			if ("11".equals(map.get("billStatus"))) {// 已到达
				if (!map.containsKey("planMileage") || map.get("planMileage").toString().length() < 1) {
					map.put("planMileage", "0");
				}
				if (!map.containsKey("travelMileage") || map.get("travelMileage").toString().length() < 1) {
					map.put("travelMileage", "0");
				}
				String reviseMileage = MapUtils.getString(map, "reviseMileage", "0");
				map.put("revisedMileage", reviseMileage);
				map.put("reviseMileage", reviseMileage);
			} else {
				if (!map.containsKey("planMileage")) {
					map.put("planMileage", "");
				} else {
					String planMileage = MapUtils.getString(map, "planMileage", "");
					map.put("planMileage", planMileage);
				}
				if (!map.containsKey("travelMileage")) {
					map.put("travelMileage", "");
				} else {
					String travelMileage = MapUtils.getString(map, "travelMileage", "");
					map.put("travelMileage", travelMileage);
				}
				String reviseMileage = MapUtils.getString(map, "reviseMileage", "0");
				map.put("reviseMileage", reviseMileage);
				map.put("revisedMileage", reviseMileage);// CCEC使用
			}
			map.put("remark", MapUtils.getString(map, "remark", ""));
			map.put("serviceCar", MapUtils.getString(map, "serviceCar", ""));
			map.put("measures", MapUtils.getString(map, "measures", ""));

			if (!map.containsKey("positionLat")) {
				map.put("positionLat", 0);
			} else {
				double positionLat = MapUtils.getDoubleValue(map, "positionLat", 0.0);
				map.put("positionLat", positionLat);
			}
			if (!map.containsKey("positionLon")) {
				map.put("positionLon", 0);
			} else {
				double positionLon = MapUtils.getDoubleValue(map, "positionLon", 0.0);
				map.put("positionLon", positionLon);
			}

			map.put("location", MapUtils.getString(map, "location", ""));
			map.put("newOrderNo", MapUtils.getString(map, "newOrderNo", ""));
			map.put("timeOutReason", MapUtils.getString(map, "timeOutReason", ""));
			map.put("secondLevelStationCode", MapUtils.getString(map, "secondLevelStationCode", ""));
			map.put("appNotAppraise", MapUtils.getIntValue(map, "appNotAppraise", -1));

			if (!map.containsKey("doneSolutionList")) {
				map.put("doneSolutionList", new ArrayList<>());
			}

			String serviceChannel = MapUtils.getString(map, "serviceChannel", "");
			if (serviceChannel.equals("CCEC")) {
				map.put("needGoOut", MapUtils.getInteger(map, "needGoOut", 1));
			} else {
				map.put("needGoOut", MapUtils.getInteger(map, "needGoOut", -1));
			}

			String goOutType = MapUtils.getString(map, "goOutType", "");
			if (goOutType.equals("1")) {
				map.put("goutMode", "2");
			} else if (goOutType.equals("2")) {
				map.put("goutMode", "3");
			} else if (goOutType.equals("3")) {
				map.put("goutMode", "1");
			} else if (goOutType.equals("4")) {
				map.put("goutMode", "0");
			} else {
				map.put("goutMode", "");
			}
			map.put("orderCategory", MapUtils.getString(map, "orderCategory", ""));
			map.put("faultReason", MapUtils.getString(map, "faultReason", ""));
			map.put("returnVisitTime", MapUtils.getString(map, "returnVisitTime", ""));
			map.put("repairerType", MapUtils.getString(map, "repairerType", ""));
			map.put("isServicecompleted", MapUtils.getString(map, "isServicecompleted", ""));
			map.put("customerName", MapUtils.getString(map, "customerName", ""));
			map.put("customerPhone", MapUtils.getString(map, "customerPhone", ""));
			map.put("customerCompany", MapUtils.getString(map, "customerCompany", ""));
			map.put("faultDesc", MapUtils.getString(map, "faultDesc", ""));
			map.put("CCSSOrderNo", MapUtils.getString(map, "CCSSOrderNo", ""));
			map.put("complainOrderType", MapUtils.getString(map, "complainOrderType", ""));
			map.put("auditResult", MapUtils.getInteger(map, "auditResult", -1));
			map.put("rejectedReason", MapUtils.getString(map, "rejectedReason", ""));
			map.put("fastestDistance", MapUtils.getString(map, "fastestDistance", ""));
			map.put("shortestDistance", MapUtils.getString(map, "shortestDistance", ""));
		} else if (intefaceName.equals("syncUserAppraisalInfoToCrm")) {
			if (!map.containsKey("crmNo")) {
				map.put("crmNo", "");
			} else {
				String crmNo = MapUtils.getString(map, "crmNo", "");
				map.put("crmNo", crmNo);
			}

			if (map.containsKey("serviceContent")) {

				String serviceContent = "";
				String serviceContentOriginal = map.get("serviceContent").toString();
				String[] serviceContentList = serviceContentOriginal.split(",");
				if (serviceContentList != null && serviceContentList.length > 0) {
					for (String serviceContentItem : serviceContentList) {
						if (serviceContentItem.contains("服务态度不满意")) {
							if (serviceContent.length() > 0) {
								serviceContent = (serviceContent + "," + "0");
							} else {
								serviceContent = "0";
							}

						}
						if (serviceContentItem.contains("服务及时性不满意")) {
							if (serviceContent.length() > 0) {
								serviceContent = (serviceContent + "," + "1");
							} else {
								serviceContent = "1";
							}
						}
						if (serviceContentItem.contains("服务能力不满意")) {
							if (serviceContent.length() > 0) {
								serviceContent = (serviceContent + "," + "2");
							} else {
								serviceContent = "2";
							}
						}
					}
					map.put("serviceContent", serviceContent);
				}

			} else {
				map.put("serviceContent", "");
			}
			if (map.containsKey("recommendDescription")) {

				String recommendDescription = "";
				String recommendDescriptionOriginal = map.get("recommendDescription").toString();
				String[] recommendDescriptionList = recommendDescriptionOriginal.split(",");
				if (recommendDescriptionList != null && recommendDescriptionList.length > 0) {
					for (String recommendDescriptionItem : recommendDescriptionList) {
						if (recommendDescriptionItem.contains("对产品不满意")) {
							if (recommendDescription.length() > 0) {
								recommendDescription = (recommendDescription + "," + "0");
							} else {
								recommendDescription = "0";
							}

						}
						if (recommendDescriptionItem.contains("对服务不满意")) {
							if (recommendDescription.length() > 0) {
								recommendDescription = (recommendDescription + "," + "1");
							} else {
								recommendDescription = "1";
							}
						}
						if (recommendDescriptionItem.contains("对整车或设备不满")) {
							if (recommendDescription.length() > 0) {
								recommendDescription = (recommendDescription + "," + "2");
							} else {
								recommendDescription = "2";
							}
						}
						if (recommendDescriptionItem.contains("其他")) {
							if (recommendDescription.length() > 0) {
								recommendDescription = (recommendDescription + "," + "3");
							} else {
								recommendDescription = "3";
							}
						}
					}
					map.put("recommendDescription", recommendDescription);
				}
			} else {
				map.put("recommendDescription", "");
			}
			if (!map.containsKey("serviceDescription")) {
				map.put("serviceDescription", "");
			} else {
				String serviceDescription = MapUtils.getString(map, "serviceDescription", "");
				map.put("serviceDescription", serviceDescription);
			}
			if (!map.containsKey("recommendReason")) {
				map.put("recommendReason", "");
			} else {
				String recommendReason = MapUtils.getString(map, "recommendReason", "");
				map.put("recommendReason", recommendReason);
			}
			String repairReasonDescription = MapUtils.getString(map, "repairReasonDescription", "");
			map.put("repairReasonDescription", repairReasonDescription);

		}

	}

	@Override
	public CRMResponeEntity getApprovalLevel(String channalName, String stationNo, String distance) {
		// TODO Auto-generated method stub
		return null;
	}

	public String getProperties(String path, String key) {
		Properties properties = new Properties();
		try {
			InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(path);
			properties.load(inputStream);
			inputStream.close();
			return properties.getProperty(key);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * @Author Joe
	 * @Description 获取CCI Crm Token
	 **/
	public Map<String, Object> getCCICrmTokenAndHost() {
		RedisClientUtils redisClientUtils = (RedisClientUtils) ApplicationContextUtils.getBean("redisClientUtils");
		if (redisClientUtils != null) {
            Map<String, String> redisMap = redisClientUtils.getMap(CRMServiceConst.CRMTOKEN_HOSTURL_CCI);
			if (MapUtils.isEmpty(redisMap)) {
				String tokenUrl = getProperties("projectconfig.properties", "crm.cci.token.host").trim();
				Map<String, Object> map = new HashMap<>();
				map.put("username", getProperties("projectconfig.properties", "crm.cci.username").trim());
				map.put("password", getProperties("projectconfig.properties", "crm.cci.password").trim());
				map.put("client_id", getProperties("projectconfig.properties", "crm.cci.clientId").trim());
				map.put("client_secret", getProperties("projectconfig.properties", "crm.cci.clientSecret").trim());
				map.put("grant_type", getProperties("projectconfig.properties", "crm.cci.grant_type").trim());
//                Map<String, Object> headerMap = new HashMap<>();
//                headerMap.put("Content-Type","application/x-www-form-urlencoded");
				JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(tokenUrl, null, map);

				LOG.info("获取CCI Crm Token结果:" + responseDate);
				if (responseDate != null && responseDate instanceof JSONObject) {

					if (responseDate.get("token_type") != null && responseDate.get("access_token") != null) {
						String token = String.format("%s %s", responseDate.get("token_type"),
								responseDate.get("access_token"));
						String host = String.format("%s/services/apexrest/", responseDate.get("instance_url"));
						Map<String, String> hostMap = new HashMap<>();
						hostMap.put("token", token);
						hostMap.put("hostUrl", host);
                        redisClientUtils.setMap(CRMServiceConst.CRMTOKEN_HOSTURL_CCI, hostMap, 60 * 6
                                * 15);
						return new HashMap<>(hostMap);
					}

				}
			} else {
				return new HashMap<>(redisMap);
			}
		}
		return null;
	}

	/**
	 * @Author Joe
	 * @Description 获取CCI Crm Token
	 **/
	public Map<String, Object> getDCECSfTokenAndHost() {
		RedisClientUtils redisClientUtils = (RedisClientUtils) ApplicationContextUtils.getBean("redisClientUtils");
		if (redisClientUtils != null) {
			Map<String, String> redisMap = redisClientUtils.getMap(CRMServiceConst.CRMTOKEN_HOSTURL_DCEC);
			if (MapUtils.isEmpty(redisMap)) {
				String tokenUrl = getProperties("projectconfig.properties", "sf.dcec.token.host").trim();
				Map<String, Object> map = new HashMap<>();
				map.put("username", getProperties("projectconfig.properties", "sf.dcec.username").trim());
				String sfDCECPassword = dictionariesTDao.getListByDTableName("sfDCECPassword");
				if(StringUtils.isBlank(sfDCECPassword)){
					sfDCECPassword = getProperties("projectconfig.properties", "sf.dcec.password");
				}
				map.put("password", sfDCECPassword.trim());
				map.put("client_id", getProperties("projectconfig.properties", "sf.dcec.clientId").trim());
				map.put("client_secret", getProperties("projectconfig.properties", "sf.dcec.clientSecret").trim());
				map.put("grant_type", getProperties("projectconfig.properties", "sf.dcec.grantType").trim());
				LOG.info("DCECtoken获取sfDCECPassword:" + sfDCECPassword);
				JSONObject responseData = CRMHttpClientUtil.httpPOSTRequest(tokenUrl, null, map);
				if (responseData != null && responseData instanceof JSONObject) {
					if (responseData.get("instance_url") != null) {
						String token = String.format("%s %s", responseData.get("token_type"),
								responseData.get("access_token"));
						String host = String.format("%s/services/apexrest/", responseData.get("instance_url"));
						Map<String, String> hostMap = new HashMap<>();
						hostMap.put("token", token);
						hostMap.put("hostUrl", host);
						redisClientUtils.setMap(CRMServiceConst.CRMTOKEN_HOSTURL_DCEC, hostMap, 60 * 6 * 15);
						return new HashMap<>(hostMap);
					}
				}
			} else {
				return new HashMap<>(redisMap);
			}
		}
		return null;
	}

	/**
	 * @Author Joe
	 * @Description 获取XCEC Crm Token
	 **/
	public Map<String, Object> getXCECCrmTokenAndHost() {
		RedisClientUtils redisClientUtils = (RedisClientUtils) ApplicationContextUtils.getBean("redisClientUtils");
		if (redisClientUtils != null) {
			Map<String, String> redisMap = redisClientUtils.getMap(CRMServiceConst.CRMTOKEN_HOSTURL_XCEC);
			if (MapUtils.isEmpty(redisMap)) {
				String tokenUrl = getProperties("projectconfig.properties", "crm.xcec.token.host").trim();
				Map<String, Object> map = new HashMap<>();
				map.put("username", getProperties("projectconfig.properties", "crm.xcec.username").trim());
				map.put("password", getProperties("projectconfig.properties", "crm.xcec.password").trim());
				map.put("client_id", getProperties("projectconfig.properties", "crm.xcec.clientId").trim());
				map.put("client_secret", getProperties("projectconfig.properties", "crm.xcec.clientSecret").trim());
				map.put("grant_type", getProperties("projectconfig.properties", "crm.xcec.grant_type").trim());
				map.put("format", getProperties("projectconfig.properties", "crm.xcec.format").trim());
				JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(tokenUrl, null, map);
				LOG.info("获取XCEC Crm Token结果:" + responseDate);
				if (responseDate != null && responseDate instanceof JSONObject) {
					if (responseDate.get("token_type") != null && responseDate.get("access_token") != null) {
						String token = String.format("%s %s", responseDate.get("token_type"),
								responseDate.get("access_token"));
						String host = String.format("%s/services/apexrest/WebAPIService/",
								responseDate.get("instance_url"));
						Map<String, String> hostMap = new HashMap<>();
						hostMap.put("token", token);
						hostMap.put("hostUrl", host);
						redisClientUtils.setMap(CRMServiceConst.CRMTOKEN_HOSTURL_XCEC, hostMap, 60 * 6 * 15);
						return new HashMap<>(hostMap);
					}
				}
			} else {
				return new HashMap<>(redisMap);
			}
		}
		return null;
	}

	/**
	 * @Author Joe
	 * @Description 同步工单状态添加确实零件信息-DBU
	 * @Date 11:38 AM 2019/8/22
	 * @Param [orderOverTime, parameters]
	 * @return void
	 **/
	public void addLackOfParts(Map<String, Object> orderOverTime, Map<String, Object> parameters) {
		if (orderOverTime != null) {
			parameters.put("timeOutReason", orderOverTime.get("ReasonMessage"));
			String partInfoString = MapUtils.getString(orderOverTime, "PartInfo", "");
			if (partInfoString.length() > 0) {
				List<Map<String, Object>> lackOfParts = new ArrayList();
				String[] partInfoArr = partInfoString.split("；|;");
				for (int i = 0; i < partInfoArr.length; i++) {
					String partInfo = partInfoArr[i];
					String[] partInfoParams = partInfo.split(",|，");
					if (partInfoParams.length == 3) {
						if (isNumeric(partInfoParams[partInfoParams.length - 1])) {
							Map<String, Object> partMap = new HashMap<>();
							for (int j = 0; j < partInfoParams.length; j++) {
								if (j == 0) {
									partMap.put("renewalPartNo", partInfoParams[0]);
								} else if (j == partInfoParams.length - 1) {
									partMap.put("quantity", partInfoParams[partInfoParams.length - 1]);
								} else {
									if (partInfoParams.length > 1) {
										partMap.put("renewalPartName", partInfoParams[1]);
									}
								}

							}
							lackOfParts.add(partMap);
						}

					}

				}
				parameters.put("lackOfParts", lackOfParts);
			}
		}
	}

	/**
	 * @Author Joe
	 * @Description 字符串转零件
	 * @Date 3:13 PM 2019/8/27
	 * @Param [renewalParts]
	 * @return java.util.List
	 **/
	public List addRenewalParts(String renewalParts) {
		List<Map<String, Object>> parts = new ArrayList<>();
		if (renewalParts != null && renewalParts.length() > 0) {
			String[] partInfoArr = renewalParts.split("；|;");

			for (int i = 0; i < partInfoArr.length; i++) {
				String partInfo = partInfoArr[i];

				String[] partInfoParams = partInfo.split(",|，");
				if (partInfoParams.length == 3) {
					if (isNumeric(partInfoParams[partInfoParams.length - 1])) {
						Map<String, Object> partMap = new HashMap<>();
						for (int j = 0; j < partInfoParams.length; j++) {
							if (j == 0) {
								partMap.put("renewalPartNo", partInfoParams[0]);
							} else if (j == partInfoParams.length - 1) {
								partMap.put("quantity", partInfoParams[partInfoParams.length - 1]);
							} else {
								if (partInfoParams.length > 1) {
									partMap.put("renewalPartName", partInfoParams[1]);
								}
							}

						}
						parts.add(partMap);
					}

				}

			}
		}
		return parts;
	}

	// 方法一：用JAVA自带的函数
	public boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	// 是否保存工单信息/状态/用户评价信息
	public boolean isSaveWorkOrder(JSONObject jsonObject) {
		if (jsonObject != null && jsonObject instanceof JSONObject) {
			if (jsonObject.containsKey("status")
					&& jsonObject.getInt("status") != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
				// 保存异常信息
				if (jsonObject.containsKey("msg") && jsonObject.get("msg") instanceof String
						&& !jsonObject.get("msg").toString().equals("null")
						&& !jsonObject.get("msg").toString().equals("NULL")
						&& jsonObject.get("msg").toString().length() > 0) {
					return true;
				}
				return true;
			}
		}
		return false;
	}

	public boolean isExceptionResponse(JSONObject jsonObject) {
		if (null == jsonObject) {
			return true;
		}
		if (jsonObject.containsKey("status")) {
			if (jsonObject.getInt("status") == CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	// 是否保存工单信息/状态/用户评价信息
	public boolean isSaveWorkOrderWithDBU(JSONObject jsonObject) {
		if (jsonObject != null && jsonObject instanceof JSONObject) {
			if (jsonObject.containsKey("status")
					&& jsonObject.getInt("status") != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
				// 保存异常信息
				return true;
			}
		}
		return false;
	}

	// 是否保存工单信息/状态/用户评价信息
	public boolean isSaveWorkOrderWithXCEC(JSONObject jsonObject) {
		if (jsonObject != null && jsonObject instanceof JSONObject) {
			if (jsonObject.containsKey("status")
					&& jsonObject.getInt("status") != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
				// 保存异常信息
				return true;
			}
		}
		return false;
	}

	/**
	 * 同步全部异常状态成功，只有有一条同步失败，需要将当前请求放到redis缓存队列
	 *
	 * @param crmPlatformServiceDao
	 * @param channelName
	 * @return
	 */
	public Boolean syncOrderStatusException(RedisClientUtils redisClientUtils,CRMPlatformServiceDao crmPlatformServiceDao, String channelName, String orderNo,Long synchroId) {
		Boolean syncSuccess = true;
        // 1、工单信息异常数据
		List<WorkOrderSynchroT> exceptionalOrderStatus = workOrderSynchroService.selectByOrderNo(orderNo);
		if (CollectionUtils.isNotEmpty(exceptionalOrderStatus)) {
			for (WorkOrderSynchroT synchro : exceptionalOrderStatus) {
				if(synchro.getSyncStatus() == 0 && !synchro.getId().equals(synchroId)) {
					Map<String, Object> params = JSON.parseObject(synchro.getOrderInfo());
					CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(channelName,
							crmPlatformServiceDao, redisClientUtils, params, synchro.getId());
					if (entity.getStatus() != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
						syncSuccess = false;
						break;
					}
				}
			}
		}
		return syncSuccess;
	}

    /**
     * 同步全部异常状态成功，只有有一条同步失败，需要将当前请求放到redis缓存队列
     *
     * @param orderNo
     * @param crmPlatformServiceDao
     * @param channelName
     * @return
     */
    public Boolean syncOrderStatusExceptionXcec(CRMPlatformServiceDao crmPlatformServiceDao, String channelName, String orderNo,Long synchroId) {
        Boolean syncSuccess = true;
		// 1、工单信息异常数据
		List<WorkOrderSynchroT> exceptionalOrderStatus = workOrderSynchroService.selectByOrderNo(orderNo);
		if (CollectionUtils.isNotEmpty(exceptionalOrderStatus)) {
			for (WorkOrderSynchroT synchro : exceptionalOrderStatus) {
				if(synchro.getSyncStatus() == 0 && !synchro.getId().equals(synchroId)){
					Map<String, Object> params = JSON.parseObject(synchro.getOrderInfo());
					CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(channelName,
							crmPlatformServiceDao, null, params,synchro.getId());
					if (entity.getStatus() != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
						syncSuccess = false;
						break;
					}
				}
			}
		}
        return syncSuccess;
    }
	// 保存异常信息到redis
	public void saveWorkOrderInfoToRedis(RedisClientUtils redisClientUtils, String redisKey, String channelName,
			Object redisData) {
		if (redisClientUtils != null) {
			Map<String, Object> exceptionMap = new HashMap<>();
			exceptionMap.put(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP, channelName);
			exceptionMap.put(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP, redisData);
			exceptionMap.put(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP, LocalTimeUtil.getCurrentTime());
			redisClientUtils.listObjectAdd(redisKey, exceptionMap);
		}
	}

	// 保存主动升级异常信息到redis
	public void saveEscalationOrderDetailToRedis(RedisClientUtils redisClientUtils, String redisKey, Object redisData) {
		if (redisClientUtils != null) {
			Map<String, Object> exceptionMap = new HashMap<>();
			exceptionMap.put(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP, redisData); // detail信息
			exceptionMap.put(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP, LocalTimeUtil.getCurrentTime()); // 时间
			redisClientUtils.listObjectAdd(redisKey, exceptionMap);
		}
	}

	private void saveExceptionSyncToRedis(String channelName, String function, String orderNo,
			Map<String, Object> parameter) {
		// 增加重试标记
		parameter.put("retry", Boolean.TRUE);
		String saveKey = CRMServiceConst.KEY_CCEC_EXCEPTION_SYNC + orderNo;
		Map<String, Object> exceptionMap = new HashMap<>();
		exceptionMap.put(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP, channelName);
		exceptionMap.put(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP, parameter);
		exceptionMap.put(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP, LocalTimeUtil.getCurrentTime());
		exceptionMap.put(CRMServiceConst.DATA_CRMPARAMS_FUNCTION, function);
		// 加入列表
		redisClient.listObjectAdd(saveKey, exceptionMap);
	}

	@Override
	public void retryExceptionSync() {
		List<String> exceptionSyncKeyList = redisClient.keys(CRMServiceConst.KEY_CCEC_EXCEPTION_SYNC + "*");
		if (CollectionUtils.isNotEmpty(exceptionSyncKeyList)) {
			for (String exceptionSyncKey : exceptionSyncKeyList) {
				retryExceptionSyncByKey(exceptionSyncKey);
			}
		}
	}

	public Boolean retryExceptionSync(String orderNo) {
		String exceptionKey = CRMServiceConst.KEY_CCEC_EXCEPTION_SYNC + orderNo;
		if (redisClient.exists(exceptionKey)) {
			return retryExceptionSyncByKey(exceptionKey);
		} else {
			return true;
		}
	}

	public Boolean retryExceptionSyncByKey(String redisKey) {
		List<Map<String, Object>> exceptionList = redisClient.getObjectList(redisKey);
		if (CollectionUtils.isEmpty(exceptionList)) {
			return true;
		} else {
			for (Map<String, Object> exceptionInfo : exceptionList) {
				String channelName = MapUtils.getString(exceptionInfo,
						CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP, "");
				String function = MapUtils.getString(exceptionInfo, CRMServiceConst.DATA_CRMPARAMS_FUNCTION, "");
				Map cacheMap = MapUtils.getMap(exceptionInfo, CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
				Map<String, Object> dataMap = (Map<String, Object>) BeanUtils.deepClone(cacheMap);
				CRMResponeEntity responseEntity = null;
				switch (function) {
				case CRMServiceConst.SYNC_ORDER_INFO:
					responseEntity = syncAppOrderInfoToCRM(channelName, crmPlatformServiceDao, redisClient, dataMap,null);
					break;
				case CRMServiceConst.SYNC_ORDER_STATUS:
					responseEntity = syncOrderStatusToCrm(channelName, crmPlatformServiceDao, redisClient, dataMap,null);
					break;
				case CRMServiceConst.SYNC_TROUBLE_SHOOTING_SUMMARY:
					responseEntity = syncTroubleshootingSummary(channelName, dataMap);
					break;
				case CRMServiceConst.SYNC_ORDER_AFFIRM:
					responseEntity = syncWorkOrderAffirm(channelName, dataMap);
					break;
				case CRMServiceConst.SYNC_CONFIRMATION_REPAIR:
					responseEntity = syncConfirmationRepair(channelName, dataMap);
					break;
				case CRMServiceConst.SYNC_REMOTE_SOLUTION:
					responseEntity = syncRemoteSolution(channelName, dataMap);
					break;
				default:
					LOG.error("工单异常重试，未知类型" + redisKey);
					return false;
				}
				if (responseEntity.getStatus() == 0) {
					redisClient.listObjectRemove(redisKey, exceptionInfo);
				} else {
					return false;
				}
			}
			return true;
		}
	}

	/**
	 * @Author Joe
	 * @Description 获取null token
	 * @Date 9:00 AM 2019/8/31
	 * @Param []
	 * @return com.cci.kangdao.crmapi.CRMResponeEntity
	 **/
	public CRMResponeEntity getNullTokenResponeEntity() {
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		responeEntity.setData(new JSONObject());
		responeEntity.setMessage("token获取失败");
		responeEntity.setStatus(-1);
		return responeEntity;
	}

	private CRMResponeEntity getSuccessEntity(String message) {
		CRMResponeEntity responseEntity = new CRMResponeEntity();
		responseEntity.setMessage(message);
		responseEntity.setStatus(0);
		responseEntity.setData(new JSONObject());
		return responseEntity;
	}

	private CRMResponeEntity getErrorEntity(String message, JSONObject data) {
		CRMResponeEntity responseEntity = new CRMResponeEntity();
		responseEntity.setMessage(message);
		responseEntity.setStatus(-1);
		if (null != data) {
			responseEntity.setData(data);
		} else {
			responseEntity.setData(new JSONObject());
		}
		return responseEntity;
	}

	@Override
	public CRMResponeEntity syncCRMWarrantyInfo(String orderNo) {
		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "") + CRMServiceConst.SYNC_CRMWARRANTY_INFO;

		Map<String, Object> map = new HashMap<>();
		map.put("AppWorkOrder", orderNo);

		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);

		LOG.info(String.format("获取索赔信息 crm响应结果：%s", responseBody));

		CRMResponeEntity responeEntity = new CRMResponeEntity();
		if (!Objects.isNull(responseBody) && responseBody.getInt("status") == 0) {
			responeEntity.setStatus(0);
			responeEntity.setMessage("success");
			responeEntity.setData(responseBody.getJSONObject("data"));
		} else {
			responeEntity.setStatus(0);
			if (!Objects.isNull(responseBody)) {
				responeEntity.setMessage(responseBody.getString("message"));
				responeEntity.setData(new JSONObject());
			}
		}
		return responeEntity;
	}

	/**
	 * APP同步客户故障位置到CRM 参数说明： { "orderNo": "WO20181107001", "caseNo": "XXX",
	 * "faultLat": 123.12, "faultLon": 123.12, "faultLocation": "XXX", "systemTime":
	 * "2019-06-19 00:00:00" "faultProvince": "XXX", "faultCity": "XXX" }
	 * orderNo、caseNo、systemTime为非必填项
	 *
	 * 返回值说明： status: 0代表请求成功，其它代表请求失败
	 *
	 */
	@Override
	public CRMResponeEntity syncFaultLocationToCRM(Map<String, Object> map) {

		LOG.info("APP同步客户故障位置到CRM:" + map);

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_FAULT_LOCATION_TOCRM;

		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);

		LOG.info("APP同步客户故障位置到CRM响应状态：" + responseBody);

		return getCRMResponeEntity(responseBody);
	}

	/**
	 * 生成返回结果
	 */
	private CRMResponeEntity getCRMResponeEntity(JSONObject responseBody) {
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		if (!Objects.isNull(responseBody) && responseBody.getInt("status") == 0) {
			responeEntity.setStatus(0);
			responeEntity.setMessage("success");
		} else {
			if (!Objects.isNull(responseBody)) {
				responeEntity.setStatus(responseBody.getInt("status"));
				if (responseBody.containsKey("msg")) {
					responeEntity.setMessage(responseBody.getString("msg"));
				} else if (responseBody.containsKey("message")) {
					responeEntity.setMessage(responseBody.getString("message"));
				}
			} else {
				responeEntity.setStatus(-1);
				responeEntity.setMessage("同步crm失败");
			}
		}
		return responeEntity;
	}

	@Override
	public CRMResponeEntity getOEMInfoFromCrmXCEC() {
		LOG.info("APP XCEC渠道获取主机厂、发动机系统、发动机用途 From CRM");

		long st = System.currentTimeMillis();
		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.GET_OEM_INFO_FROM_CRM_XCEC;

		JSONObject responseBody = CRMHttpClientUtil.httpGETRequest(channelHost, headerParameter, null);

		long et = System.currentTimeMillis() - st;
		LOG.info(String.format("APP XCEC渠道获取主机厂、发动机系统、发动机用途FromCRM结束 响应数据：%s  消耗时间: %d", responseBody, et));

		if (null == responseBody) {
			return getCRMResponeEntity(-1, "crm请求失败", null);
		} else {
			return getCRMResponeEntity(responseBody.getInt("status"), responseBody.getString("msg"),
					responseBody.getJSONObject("data"));
		}

	}

	@Override
	public CRMResponeEntity getOEMInfoFromCrmByEsnXCEC(String esn) {
		LOG.info("APP XCEC渠道获取esn对应的主机厂、发动机系统、发动机用途 From CRM  esn: " + esn);

		long st = System.currentTimeMillis();
		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.GET_OEM_INFO_FROM_CRM_ESN_XCEC;
		// 请求参数
		Map<String, Object> parameter = new HashMap<>();
		parameter.put("ESN", esn);
		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameter);

		long et = System.currentTimeMillis() - st;
		LOG.info(String.format("APP XCEC渠道获取esn对应的主机厂、发动机系统、发动机用途FromCRM结束 响应数据：%s  消耗时间: %d", responseBody, et));

		if (null == responseBody) {
			return getCRMResponeEntity(-1, "crm请求失败", null);
		} else {
			return getCRMResponeEntity(responseBody.getInt("status"), responseBody.getString("msg"),
					responseBody.getJSONObject("data"));
		}

	}

	private CRMResponeEntity getCRMResponeEntity(int status, String message, JSONObject data) {
		CRMResponeEntity crmResponeEntity = new CRMResponeEntity();
		crmResponeEntity.setStatus(status);
		crmResponeEntity.setMessage(message);
		crmResponeEntity.setData(data);
		return crmResponeEntity;
	}

	/**
	 *    * "ESN":"12345678", 必填    * "accountId":"0017F000026vAG6QAM", 必填    *
	 * "procurementTime":"2021-4-13", 必填
	 *
	 *    * "workMileages":10,    * "workHours":null, 必填(二选一)
	 *
	 *    * "customerName":"Test 1", 必填    * "phoneNumber":"13456765432", 必填    *
	 * "series":"ISM", 必填    * "appArea":"客车", 必填    * "needGoOut":1, 必填
	 *
	 *    * "faultLocation":"teste2 e2",    * "faultLat":12.213,    *
	 * "faultLon":32.4234,    * "vehicleType": 1, 必填(如果needGoOut为1(外出)，这4个字段必填)
	 *
	 *
	 *    * "remark":"Test" "orderNo":"12321", "equipmentNo":"", "orderSource":4,
	 * "serviceCar":"12321", "faultDesc":"123", "creatPerson":"App Name",
	 * "creatTime":"2020-11-02 01:50:00", "stationNo":"02121"
	 *
	 * "needGoOut" 是否外出 0:否 1:是，并传入faultLocation，faultLat，faultLon，vehicleType。
	 * "vehicleType" 对应的选项 火车-> 1，飞机-> 2，公交->3，自驾->4
	 */
	@Override
	public CRMResponeEntity syncSaleWorkOrderToCrmXCEC(Map<String, Object> map,WorkOrderSynchroT workOrderSynchro) {
		LOG.info("APP XCEC渠道 同步售时工单信息到CRM  请求参数：" + map);
		long st = System.currentTimeMillis();
		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
		if (tokenAndHostMap == null || tokenAndHostMap.isEmpty()) {
			LOG.error("XCEC 同步工单信息获取token失败；打印参数" + JsonUtils.toJsonString(map));
			workOrderSynchro.setFailReason("获取token失败");
			workOrderSynchro.setSyncStatus(0);
			return this.getNullTokenResponeEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);

		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_WORKORDER_TO_CRM_XCEC;

		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);
		long et = System.currentTimeMillis() - st;

		LOG.info(String.format("APP XCEC渠道 同步售时工单信息到CRM结束 响应数据：%s  消耗时间: %d", responseBody, et));

		/**
		 * 响应的数据格式 { "status": 0, "msg": "返回的信息", "data":{ "orderNo": "售时工单编号", "crmNo":
		 * "crm编号" } }
		 *
		 * 返回值说明： status 0:成功 其它:失败 msg 返回消息信息 data 当 status != 0时，data为null
		 *
		 */
		if (null == responseBody) {
			return getCRMResponeEntity(-1, "crm响应失败", null);
		} else {
			// 响应成功时获取响应的orderNo crmNo
			if (responseBody.getInt("status") == 0) {
				String orderNo = responseBody.getString("orderNo");
				String crmNo = responseBody.getString("crmNo");
				JSONObject data = new JSONObject();
				data.put("orderNo", orderNo);
				data.put("crmNo", crmNo);
				return getCRMResponeEntity(responseBody.getInt("status"), responseBody.getString("msg"), data);
			}
			return getCRMResponeEntity(responseBody.getInt("status"), responseBody.getString("msg"), null);
		}
	}

	@Override
	public CRMResponeEntity syncOverTimeReasonToXCECCRM(java.util.Map<String, Object> map) {
		LOG.info("XCEC同步技师维修超时原因 参数：" + map);

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getXCECCrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addXCECEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_OVERTIMEREASON_TOXCECCRM;
		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);

		LOG.info("XCEC同步技师维修超时原因 响应：" + responseBody);

		return getCRMResponeEntity(responseBody);
	}

	@Override
	public CRMResponeEntity syncFaultInfoToCRM(String channalName, CRMPlatformServiceDao serviceDao,
			RedisClientUtils redisClientUtils, List parameters, String orderNo) {
		/**
		 * 1、初始化响应实体
		 */
		CRMResponeEntity verifyResponse = this.verifyParameters(channalName);
		if (verifyResponse.getStatus() == CRMServiceConst.CHANNEL_VERIFY_FAILURE) {
			return verifyResponse;
		}

		/**
		 * 3、判断渠道
		 **/
		if (channalName.equals(CRMServiceConst.DCEC) || channalName.equals(CRMServiceConst.DCEC_TEST)) {

//            if (redisClientUtils != null) { // APP操作同步，非重传，参数需要座处理
//                // 请求Param参数
//                this.addInterfaceNullParameters("syncOrderStatusToCrm",parameters);
//                if (parameters.get("CRMNo").toString().length() > 0){// 传过来了CRMNo
//
//                }else {
//                    String CRMNo = serviceDao.getCRMOrderNoByAPPOrderNo(parameters.get("orderNo").toString());
//                    if (CRMNo != null && CRMNo.length() > 0){
//                        parameters.put("CRMNo",CRMNo);
//                    }
//                }
//                // 判断如果是服务经理选择"用户不需要维修"，则关闭工单
//                if ("3".equals(parameters.get("billStatus"))) { // 服务经理审核不通过
//                    if (parameters.containsKey("refuseType") && "2".equals(parameters.get("refuseType"))) {//用户不需要维修
//                        parameters.put("billStatus", 15);
//                    }
//                }
//                double positionLat = MapUtils.getDoubleValue(parameters,"positionLat",0.0);
//                double positionLon = MapUtils.getDoubleValue(parameters,"positionLon",0.0);
//                parameters.put("positionLat", positionLon);
//                parameters.put("positionLon", positionLat);
//            }

			// JSONObject jsonBodyParameter = JSONObject.fromObject(parameters);
			// com.alibaba.fastjson.JSONObject jsonBodyParameter =
			// com.alibaba.fastjson.JSONObject.parseObject(
			// com.alibaba.fastjson.JSON.toJSONString(parameters));

			// 请求body参数
			Map<String, Object> requestParameter = new HashMap<String, Object>();
			requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, CRMServiceConst.SYNC_FAULTINFO_TOCRM);
			requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, parameters.toString());

			// DCEC获取token及host
			Map<String, Object> map = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(map)){
				return this.getNullTokenResponeEntity();
			}
			Map<String, Object> headerParameter = this.addDCECEncryptionHeader(MapUtils.getString(map, "token"));
			String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.SYNC_FAULTINFO_TOCRM;

			// 判断是否redisClientUtils为空，如果为空则是异常状态重传，异常数据重传不需要保存当前状态
//            Boolean syncSuccess = true;
//            String redisOrderNo = MapUtils.getString(parameters,"orderNo","");
//            String redisKey = String.format("%s%s",CRMServiceConst.KEY_DCEC_ORDERSTATUS_APP,redisOrderNo);
//            if (redisClientUtils != null){
//                syncSuccess = syncOrderStatusException(redisKey,redisClientUtils,serviceDao,channalName,parameters);
//            }

//            if (syncSuccess){
//                LOG.info("DCEC开始同步到CRM系统参数信息：" + JsonUtils.toJsonString(parameters)
//                        + "请求头信息：" + JsonUtils.toJsonString(headerParameter));
			JSONObject responseDate = new JSONObject();
			boolean flag = true;
			int num = 1;
			while (flag) {
				try {
					responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
							MapUtils.getString(map, "token"), parameters.toString());
					/**
					 * 4、服务器异常/超时/关闭，需要保存到redis数据库
					 **/
//                    if (isSaveWorkOrder(responseDate)) {
//                        this.saveWorkOrderInfoToRedis(redisClientUtils,redisKey,channalName,parameters);
//                    }
					// 将响应消息转换成响应实体类
					return this.getResponeEntity(responseDate, "数据同步成功");
				} catch (Exception e) {
					// APP同步工单信息到CRM系统失败
					LOG.error("同步多故障信息失败：" + e.getMessage(), e);
					JSONObject obj = new JSONObject();
					obj.put("exception", e.toString());
					obj.put("params", parameters);
					redisClientUtils.setObject(CRMServiceConst.FAULT + orderNo, obj, 0);
				}
				num++;
				if (num == 3) {
					flag = false;
				}
			}

			/**
			 * 4、服务器异常/超时/关闭，需要保存到redis数据库
			 **/
//                if (isSaveWorkOrder(responseDate)){
//
//                    this.saveWorkOrderInfoToRedis(redisClientUtils,redisKey,channalName,parameters);
//                }
			// 将响应消息转换成响应实体类
			return this.getResponeEntity(responseDate, "数据同步失败");
		}
		// 配置响应实体 message、status数据
		CRMResponeEntity responeEntity = new CRMResponeEntity();
		responeEntity.setMessage("渠道不对");
		responeEntity.setStatus(-1);
		responeEntity.setData(new JSONObject());
		return responeEntity;
	}

	/**
	 * @description: DCEC验证站长、技师、信息员SF系统是否存在
	 * @param: null
	 * @return:
	 * @exception:
	 * @author: wunan
	 * @company: Pactera Technology Co.,Ltd
	 * @since: 2021/8/10 15:42
	 * @version: V1.0
	 */
	@Override
	public CRMResponeEntity validationDCECUserInfo(String channalName, String userPhone, Integer userRole,
												   String userName, Long serviceStationId) {
		LOG.info("验证站长、技师、信息员SF系统是否存在:" + userPhone + "-" + userRole + "-" + userName);
		/**
		 * 1、初始化响应实体
		 */
		CRMResponeEntity verifyResponse = this.verifyParameters(channalName);
		if (verifyResponse.getStatus() == CRMServiceConst.CHANNEL_VERIFY_FAILURE) {
			return verifyResponse;
		}
		if (channalName.equals(CRMServiceConst.DCEC) || channalName.equals(CRMServiceConst.DCEC_TEST)) {
			Map<String, Object> parameters = new HashMap<String, Object>() {
				private static final long serialVersionUID = 234429996046931310L;
				{
					put("userPhone", userPhone);
					put("userRole", userRole);
					put("userName", userName);
				}
			};
			// 如果传一网的serviceStationId则传一网鉴定号，如果传二网的serviceStationId则将二网以及所属一网的鉴定号都传入
			// （数据结构目前设计的是支持一个二网对应多个一网的，但是目前现状是一个二网只能属于一个一网，如果后续需求变更需要支持多对多关系的话，此验证接口还要再讨论修改入参定义。）
//			fatherStationNo	一网鉴定号	String
//			stationNo	二网鉴定号	String
			ServiceStationT serviceStationT = serviceStationDao.getSSById(serviceStationId);
			SSRepairT sSRepairT = sSRepairTDao.getSSRepairTByCompanyNoAndServiceStationID(CRMServiceConst.DCEC,
					serviceStationId);
			int relationType = serviceStationT.getRelationType() == null ? 1 : serviceStationT.getRelationType();
			if (relationType == 1) {// 一网
				parameters.put("fatherStationNo", sSRepairT.getBusinessno());
			} else {
				SSRepairT fatherSSRepairT = sSRepairTDao
						.getSSRepairTByCompanyNoAndChildServiceStationID(CRMServiceConst.DCEC, serviceStationId);
				parameters.put("fatherStationNo", fatherSSRepairT.getBusinessno());
				parameters.put("stationNo", sSRepairT.getBusinessno());
			}
			// 请求body参数
			Map<String, Object> requestParameter = new HashMap<String, Object>();
			requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, CRMServiceConst.GET_VALIDATIONUSERINFO_FROM_CRM);
			requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, parameters.toString());

			// DCEC获取token及host
			Map<String, Object> map = getDCECSfTokenAndHost();
			if(MapUtils.isEmpty(map)){
				return this.getNullTokenResponeEntity();
			}
			String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.GET_VALIDATIONUSERINFO_FROM_CRM;

			try {
				JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost,
						MapUtils.getString(map, "token"), JsonUtils.toJsonString(parameters));
				// 将响应消息转换成响应实体类
				return this.getResponeEntity(responseDate, "接口请求成功");
			} catch (Exception e) {
				// 请求响应失败
				LOG.error("同步多故障信息失败：" + e.getMessage(), e);
				JSONObject obj = new JSONObject();
				obj.put("exception", e.toString());
				obj.put("params", parameters);
				return this.getResponeEntity(obj, "接口请求失败");
			}
		}
		return this.getErrorEntity("渠道不匹配", null);
	}

	/**
	 * 3.3.0 同步主动升级工单详情到DBU retryKey：1-为重试，0-首次
	 */
	@Async
	@Override
	public CRMResponeEntity syncEscalationOrderDetail(EscalationOrderT escalationOrder, Integer retryKey) {
		LOG.info("主动升级工单详情-同步至DBU  详情：" + escalationOrder);
		// 1. 判断最后的方案处理人角色
		EscalationReasonT lastReason = escalationReasonTDao.getLastReasonByOrderId(escalationOrder.getId());
		GetEscalationOrderDetailResponse detailResponse;
		if (lastReason.getEscalationType()
				.equals(TypeDictionary.ESCALATIONTYPE_TECHNICIAN_TO_FIELDENGINEER.getCode())) {
			// 1.1 升级到区域工程师时解决的
			detailResponse = escalationService.getEscalationOrderDetail(escalationOrder.getId(), "R0074");
		} else {
			// 1.2 升级到服务专家时解决的
			detailResponse = escalationService.getEscalationOrderDetail(escalationOrder.getId(), "R0091");
		}

		// 2. 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		if (tokenAndHostMap == null) {
			throw new CommonException(ExceptionStatus.TOKEN_ERROR.getStatus(),
					ExceptionStatus.TOKEN_ERROR.getMessage());
		}

		// 3. 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);

		// 4. 调取请求 -- 待确认地址
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_ESCALATIONORDERDETAIL_TOCRM;
		JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter,
				(Map<String, Object>) detailResponse);
		LOG.info("主动升级工单详情-同步至DBU  返回数据：" + responseDate);

		// 5. 保存异常工单数据到redis和DB
		if (isSaveWorkOrderWithDBU(responseDate)) {
			if (retryKey == 0) { // 若首次尝试
				this.saveEscalationOrderDetailToRedis(redisClientUtils,
						CRMServiceConst.ESCALATION_SYNC_EXCEPTION_DETAIL, escalationOrder.getId());
			}
			// 保存到DB
			APIExceptionT exceptionT = new APIExceptionT();
			exceptionT.setAPIName("syncEscalationOrderDetail");
			exceptionT.setData(detailResponse.toString());
			exceptionT.setExceptionInfo(responseDate.toString());
			exceptionT.setCompanyNo("DBU");
			exceptionT.setSystemTime(LocalTimeUtil.getRealCurrentTime());
			exceptionT.setDirection(0); // 不知道是个啥意思
			crmPlatformServiceDao.saveExceptionToExpTable(exceptionT);
		} else {
			CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
			return responeEntity;
		}
		return null;
	}

	@Override
	public CRMResponeEntity getStationListByCrm(String channalName) {
		Map<String, Object> parameters = new HashedMap();
		parameters.put("caseId", channalName);
		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		headerParameter.put("Content-Type", "application/json;charset=UTF-8");

		LOG.info("获取dbu----CRM服务站集合-----参数：" + JsonUtils.toJsonString(parameters) + "请求头信息："
				+ JsonUtils.toJsonString(headerParameter));
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.GET_DEALERS_BY_CASE_ID;
		LOG.info("获取dbu----CRM服务站集合-----地址：" + channelHost);
		JSONObject responseDate = CRMHttpClientUtil.httpGETRequest(channelHost, headerParameter, parameters);
		// 将响应消息转换成响应实体类
		return this.getResponeEntityStr(responseDate, "数据获取成功");
	}

	public void syncServiceAgreementAndEngineToCRM(AccountEngineRelaRequest accountEngineRelaRequest) {
		String jsonBody = JsonUtils.toJsonString(accountEngineRelaRequest);
		// 请求body参数
		Map<String, Object> requestParameter = new HashMap<>();
		requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, jsonBody);
		// 添加请求头
		Map<String, Object> headerParameter = new HashMap<String, Object>();
		// 调取请求
		String tokenUrl = getProperties("projectconfig.properties", "crm.cci.token.host").trim();
		Map<String, Object> map = new HashMap<>();
		Map<String, String> hostMap = new HashMap<>();
		String hostUrl = "";
		map.put("username", getProperties("projectconfig.properties", "crm.cci.username").trim());
		map.put("password", getProperties("projectconfig.properties", "crm.cci.password").trim());
		map.put("client_id", getProperties("projectconfig.properties", "crm.cci.clientId").trim());
		map.put("client_secret", getProperties("projectconfig.properties", "crm.cci.clientSecret").trim());
		map.put("grant_type", getProperties("projectconfig.properties", "crm.cci.grant_type").trim());

		JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(tokenUrl, null, map);
		LOG.info("获取CCI Crm Token结果:" + responseDate);
		if (responseDate != null && responseDate instanceof JSONObject) {
			if (responseDate.get("token_type") != null && responseDate.get("access_token") != null) {
				String token = String.format("%s %s", responseDate.get("token_type"), responseDate.get("access_token"));
				String host = String.format("%s/services/apexrest/pushAccountEngineRelation",
						responseDate.get("instance_url"));
				hostMap.put("token", token);
				hostMap.put("hostUrl", host);
			}
		}
		if (hostMap != null && hostMap.containsKey("hostUrl") && hostMap.get("hostUrl") != null) {
			hostUrl = hostMap.get("hostUrl");
		}
		if (hostUrl.length() != 0) {
			headerParameter.put("Authorization", hostMap.get("token"));
			headerParameter.put("Content-Type", "EngineRelation");
			LOG.info("CCI开始同步主动升级服务信息到CRM系统参数信息：" + jsonBody);

			JSONObject responseData = CRMHttpClientUtil.httpPOSTRequest(hostUrl, headerParameter, requestParameter);
			if (!responseData.get("status").equals("success")) {
				APIExceptionT apiExceptionT = new APIExceptionT();
				apiExceptionT.setAPIName(accountEngineRelaRequest.getMasNumber());// 当前传输的序号，用于定位日志
				apiExceptionT.setData(jsonBody);
				apiExceptionT.setCompanyNo("1");
				apiExceptionT.setExceptionInfo(JsonUtils.toJsonString(responseData));
				apiExceptionT.setFlag(0);
				apiExceptionT.setSystemTime(LocalTimeUtil.getRealCurrentTime());
				crmServiceDao.saveExceptionToExpTable(apiExceptionT);
			}
		}
	}

	@Override
	public CRMResponeEntity validationCert(Long serviceStationID, String orderType) {
		LOG.info("SF验证资质接口服务:" + serviceStationID);
		SSRepairT ssRepairT = sSRepairTDao.getSSRepairTByCompanyNoAndServiceStationID(CRMServiceConst.DCEC,
				Long.valueOf(serviceStationID));
		JSONObject responseDate = new JSONObject();
		if (ssRepairT == null) {
			responseDate.put("status", 0);
			responseDate.put("data", new JSONObject().put("hasQualify", 0));// 没资质
			return this.getResponeEntity(responseDate, "接口请求成功");
		}
		if (StringUtils.isEmpty(orderType) || orderType == null) {
			orderType = "0";
		}
		String finalOrderType = orderType;
		Map<String, Object> parameters = new HashMap<String, Object>() {
			private static final long serialVersionUID = 234429996046931310L;
			{
				put("stationNo", ssRepairT.getBusinessno());
				put("orderType", finalOrderType);
			}
		};
		// 请求body参数
		Map<String, Object> requestParameter = new HashMap<String, Object>();
		requestParameter.put(CRMServiceConst.CRM_REQUEST_FUNNAME, CRMServiceConst.GET_VALIDATIONCERT_FROM_CRM);
		requestParameter.put(CRMServiceConst.CRM_REQUEST_PARAMS, parameters.toString());
		// DCEC获取token及host
		Map<String, Object> map = getDCECSfTokenAndHost();
		if(MapUtils.isEmpty(map)){
			return this.getNullTokenResponeEntity();
		}
		String channelHost = MapUtils.getString(map, "hostUrl") + CRMServiceConst.GET_VALIDATIONCERT_FROM_CRM;
		try {
			JSONObject date = CRMHttpClientUtil.httpPOSTRequestForDCEC(channelHost, MapUtils.getString(map, "token"),
					JsonUtils.toJsonString(parameters));
			// 将响应消息转换成响应实体类
			return this.getResponeEntity(date, "接口请求成功");
		} catch (Exception e) {
			// 请求响应失败
			LOG.error("APP验证资质接口失败：" + e.getMessage(), e);
			return this.getErrorEntity("APP验证资质接口失败：" + e.getMessage(), null);
		}
	}


	@Override
	@Transactional
	public CRMResponeEntity syncRepairAckToCRM(String channelName, CRMPlatformServiceDao serviceDao,
												  RedisClientUtils redisClientUtils, Map<String, Object> parameter) {

		if (channelName.equals(CRMServiceConst.DCEC) || channelName.equals(CRMServiceConst.DCEC_TEST)) {
			return null;
		} else if (channelName.equals(CRMServiceConst.XCEC) || channelName.equals(CRMServiceConst.XCEC_TEST)) {
			return null;
		} else if (channelName.equals(CRMServiceConst.BFCEC) || channelName.equals(CRMServiceConst.BFCEC_TEST)) {
			return null;
		} else if (channelName.equals(CRMServiceConst.DBU) || channelName.equals(CRMServiceConst.DBU_TEST)) {
			// 添加加密请求头
			Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
			if (tokenAndHostMap == null || tokenAndHostMap.isEmpty()) {
				LOG.error("DBU 同步工单信息获取token失败；打印参数" + JsonUtils.toJsonString(parameter));
				return this.getNullTokenResponeEntity();
			}
			// 添加token请求头
			Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
			// 调取请求
			String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
					+ CRMServiceConst.SYNC_WOSRTANDWFC_TOCRM;
			JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameter);
			// 将响应消息转换成响应实体类
			CRMResponeEntity responeEntity = this.getResponeEntity(responseDate, "数据获取成功");
			return responeEntity;
		}
		return null;
	}






	public CRMResponeJSONArrayEntity getResponeJSONArrayEntity(JSONObject responseDate, String message) {
		CRMResponeJSONArrayEntity crmResponeJSONArrayEntity = new CRMResponeJSONArrayEntity();
		if (null == responseDate) {
			crmResponeJSONArrayEntity.setMessage("crm信息获取失败");
			crmResponeJSONArrayEntity.setStatus(-1);
			crmResponeJSONArrayEntity.setResult("不存在");
		} else {
			if (responseDate.containsKey("status") && responseDate.getInt("status") == 0) { // 成功
				// 配置响应实体 data数据
				if (responseDate.containsKey("data") && responseDate.get("data") != null) {
					// JSONArray
					if (responseDate.get("data") instanceof JSONArray) {
						JSONArray jsonObject = responseDate.getJSONArray("data");
						crmResponeJSONArrayEntity.setData(jsonObject);
					} else {
						crmResponeJSONArrayEntity.setData(new JSONArray());
					}
				} else {
					crmResponeJSONArrayEntity.setData(new JSONArray());
				}
				// 配置响应实体 message、status数据
				crmResponeJSONArrayEntity.setMessage(message);
				crmResponeJSONArrayEntity.setStatus(0);
				crmResponeJSONArrayEntity.setResult((responseDate.containsKey("result") && responseDate.get("result") != null)?responseDate.get("result").toString():"不存在");
			} else {// 失败
				// 配置响应实体 message、status数据
				if (responseDate.containsKey("msg") && responseDate.get("msg") != null) {
					crmResponeJSONArrayEntity.setMessage(responseDate.get("msg").toString());
				}
				if (responseDate.containsKey("message") && responseDate.get("message") != null && StringUtils.isEmpty(crmResponeJSONArrayEntity.getMessage())) {
					crmResponeJSONArrayEntity.setMessage(responseDate.get("message").toString());
				}
				if (responseDate.containsKey("status") && responseDate.get("status") != null) {
					crmResponeJSONArrayEntity.setStatus(Integer.valueOf(responseDate.get("status").toString()));
				} else {
					crmResponeJSONArrayEntity.setStatus(-1);
				}
				if (responseDate.containsKey("data") && responseDate.get("data") != null) {
					if (responseDate.get("data") instanceof JSONArray) {
						crmResponeJSONArrayEntity.setData(responseDate.getJSONArray("data"));
					} else {
						crmResponeJSONArrayEntity.setData(new JSONArray());
					}

				} else {
					crmResponeJSONArrayEntity.setData(new JSONArray());
				}
				crmResponeJSONArrayEntity.setResult((responseDate.containsKey("result") && responseDate.get("result") != null)?responseDate.get("result").toString():"不存在");
			}
		}
		return crmResponeJSONArrayEntity;
	}


	public CRMResponeJSONArrayEntity getNullTokenResponeJSONArrayEntity() {
		CRMResponeJSONArrayEntity responeEntity = new CRMResponeJSONArrayEntity();
		responeEntity.setData(new JSONArray());
		responeEntity.setMessage("token获取失败");
		responeEntity.setStatus(-1);
		responeEntity.setResult("不存在");
		return responeEntity;
	}



	@Override
	public CRMResponeJSONArrayEntity checkCampaignTask(Map<String, Object> map) {
		LOG.info("dbu获取campaign任务列表，参数：" + map);

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeJSONArrayEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.CHECK_CAMPAIGN_TASK;
		if(map.containsKey("request")){
			map.remove("request");
		}
		if(map.containsKey("response")){
			map.remove("response");
		}
		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);
		responseBody.forEach((k, v) -> {});
		LOG.info("dbu获取campaign任务列表 响应：" + responseBody);
		String jsonString = JSON.toJSONString(responseBody);
		if (jsonString.contains("null")) {
			jsonString = jsonString.replaceAll("null", "\\\"\\\"");
		}
		JSONObject responseDateNotNull = JSONObject.fromObject(jsonString);
		return getResponeJSONArrayEntity(responseDateNotNull,"数据获取成功");
	}


	@Override
	public CRMResponeJSONArrayEntity syncDealerCampaignOptionToSF(Map<String, Object> map) {
		LOG.info("dbu同步campaign任务状态，参数：" + map);

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeJSONArrayEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_DEALER_CAMPAIGN_OPTION_TO_SF;
		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);

		LOG.info("dbu同步campaign任务状态 响应：" + responseBody);
		return getResponeJSONArrayEntity(responseBody,"数据获取成功");
	}


	@Override
	public CRMResponeJSONArrayEntity syncDealerCampaignStatusToSF(Map<String, Object> map) {
		LOG.info("dbu同步campaign任务维修完成状态，参数：" + map);

		// 添加加密请求头
		Map<String, Object> tokenAndHostMap = this.getCCICrmTokenAndHost();
		if (tokenAndHostMap == null) {
			return this.getNullTokenResponeJSONArrayEntity();
		}
		// 添加token请求头
		Map<String, Object> headerParameter = this.addCCIEncryptionHeader(tokenAndHostMap);
		// 调取请求
		String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "")
				+ CRMServiceConst.SYNC_DEALER_CAMPAIGN_STATUS_TO_SF;
		JSONObject responseBody = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, map);

		LOG.info("dbu同步campaign任务维修完成状态 响应：" + responseBody);
		return getResponeJSONArrayEntity(responseBody,"数据获取成功");
	}

}
